天天看点

数据库连接池--自定义连接池

什么是连接池

传统的开发模式下,Servlet处理用户的请求,找DAO查询数据,DAO会创建与数据库之间的链接,完成数据查询后会关闭数据库的链接。

这样的方式会导致用户每次请求都要向数据库建立链接而数据库创建连接通常需要消耗相对较大的资源,创建时间也较长。假设网站一天10万访问量,数据库服务器就需要创建10万次连接,极大的浪费数据库的资源,并且极易造成数据库服务器内存溢出、宕机。

解决方案就是数据库连接池

连接池就是数据库连接对象的一个缓冲池

我们可以先创建10个数据库连接缓存在连接池中,当用户有请求过来的时候,DAO不必创建数据库连接,而是从数据库连接池中获取一个,用完了也不必关闭连接,而是将连接换回池子当中,继续缓存

使用数据库连接池可以极大地提高系统的性能

实现数据库连接池

jdbc针对数据库连接池也定义的接口java.sql.DataSource,所有的数据库连接池实现都要实现该接口

该接口中定义了两个重载的方法

Connection getConnection()

Connection getConnection(String username, String password)

数据库连接池实现思路

1) 定义一个类实现java.sql.DataSource接口

2) 定义一个集合用于保存Connection对象,由于频繁地增删操作,用LinkedList比较好

3) 实现getConnection方法,在方法中取出LinkedList集合中的一个连接对象返回

注意:

用户用完Connection,会调用close方法释放资源,此时要保证连接换回连接池,而不是关闭连接,因而需要对其close方法进行增强

连接池代码示例:

package com.my.pool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;

public class MyPoolJdbcUtil {
	//	1.存在一个池(集合) 
	private static LinkedList<Connection> pool = new LinkedList<Connection>();  //添加和删除比较频繁
	//1.1存放若干链接--3
	static {
		try {
			for(int i = 0 ; i< 3 ; i++){
				// 获得一个链接
				Class.forName("com.mysql.jdbc.Driver");
				Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8","root","1234");
				// 添加到pool
				//pool.add(conn);
				pool.add(new MyConnection(conn, pool));
			}
		}  catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//	2.当获得时,从池中移除
	public static Connection getConnection(){
		// 2.1 处理pool没有数据
		if(pool.isEmpty()){
			// 等待
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
			}
			// 如果是空,再从pool获取
			return getConnection();  //递归
		} else {
			return pool.removeFirst();
		}
	}

	//	3.当释放时,将链接归回池
	public static void closeResource(Connection conn ,Statement st , ResultSet rs){
		try {
			if(rs != null){
				rs.close();
			}
		} catch (SQLException e) {
			throw new RuntimeException(e.getMessage(),e);
		} finally {
			try {
				if(st != null){
					st.close();
				}
			} catch (SQLException e) {
				throw new RuntimeException(e.getMessage(),e);
			} finally {
				try {
					if(conn != null){
						//conn.close();
						pool.add(conn); //将链接归回池
					}
				} catch (Exception e) {
					throw new RuntimeException(e.getMessage(),e);
				}
			}
		}
		
	}

}

           

close方法的增强实现:

package com.my.pool;

import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * 目标:增强mysql的com.mysql.jdbc.Connection类,mysql的实现了java.sql.Connection接口
 * 1、自定义类A需要实现接口B,实现的接口是需要增强类具有的接口
 * 2、自定义类A需要一个可以接收接口B的实现类的构造方法
 * 3、自定义类A需要将接口B的具体实现类缓存
 * 4、实现需要增强的方法 close
 * 5、其他不需要增强的方法,直接调用接口B的具体实现类的方法
 */

public class MyConnection implements Connection {
	private Connection conn;
	private List<Connection> pool;
	
	public MyConnection(Connection conn){
		this.conn = conn;
	}
	
	/* 因为与自定义连接池有关系,所以需要另外添加一个构造方法 */
	public MyConnection(Connection conn,List<Connection> pool){
		this.conn = conn;
		this.pool = pool;
	}
	
	/* 以下是增强的方法 */
	
	@Override
	public void close() throws SQLException {
		//将调用当前close的链接Connection对象添加到链接池中
		System.out.println("连接池归还中..." + this);
		this.pool.add(this);
	}
	
	/* 以下是不需要增强的方法  */
	
	@Override
	public void commit() throws SQLException {
		this.conn.commit();
	}

	@Override
	public void clearWarnings() throws SQLException {
		this.conn.clearWarnings();
	}

	@Override
	public Array createArrayOf(String typeName, Object[] elements)
			throws SQLException {
		return this.conn.createArrayOf(typeName, elements);
	}

	@Override
	public Blob createBlob() throws SQLException {
		return this.conn.createBlob();
	}

	@Override
	public Clob createClob() throws SQLException {
		return this.conn.createClob();
	}

	@Override
	public NClob createNClob() throws SQLException {
		return this.conn.createNClob();
	}

	@Override
	public SQLXML createSQLXML() throws SQLException {
		return this.conn.createSQLXML();
	}

	@Override
	public Statement createStatement() throws SQLException {
		return this.conn.createStatement();
	}

	@Override
	public Statement createStatement(int resultSetType,
			int resultSetConcurrency, int resultSetHoldability)
			throws SQLException {
		return this.conn.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
	}

	@Override
	public Statement createStatement(int resultSetType, int resultSetConcurrency)
			throws SQLException {
		return this.conn.createStatement(resultSetType, resultSetConcurrency);
	}

	@Override
	public Struct createStruct(String typeName, Object[] attributes)
			throws SQLException {
		return this.conn.createStruct(typeName, attributes);
	}

	@Override
	public boolean getAutoCommit() throws SQLException {
		return this.conn.getAutoCommit();
	}

	@Override
	public String getCatalog() throws SQLException {
		return this.conn.getCatalog();
	}

	@Override
	public Properties getClientInfo() throws SQLException {
		return this.conn.getClientInfo();
	}

	@Override
	public String getClientInfo(String name) throws SQLException {
		return this.conn.getClientInfo(name);
	}

	@Override
	public int getHoldability() throws SQLException {
		return this.conn.getHoldability();
	}

	@Override
	public DatabaseMetaData getMetaData() throws SQLException {
		return this.conn.getMetaData();
	}

	@Override
	public int getTransactionIsolation() throws SQLException {
		return this.conn.getTransactionIsolation();
	}

	@Override
	public Map<String, Class<?>> getTypeMap() throws SQLException {
		return this.conn.getTypeMap();
	}

	@Override
	public SQLWarning getWarnings() throws SQLException {
		return this.conn.getWarnings();
	}

	@Override
	public boolean isClosed() throws SQLException {
		return this.conn.isClosed();
	}

	@Override
	public boolean isReadOnly() throws SQLException {
		return this.conn.isReadOnly();
	}

	@Override
	public boolean isValid(int timeout) throws SQLException {
		return this.conn.isValid(timeout);
	}

	@Override
	public String nativeSQL(String sql) throws SQLException {
		return this.conn.nativeSQL(sql);
	}

	@Override
	public CallableStatement prepareCall(String sql, int resultSetType,
			int resultSetConcurrency, int resultSetHoldability)
			throws SQLException {
		return this.conn.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
	}

	@Override
	public CallableStatement prepareCall(String sql, int resultSetType,
			int resultSetConcurrency) throws SQLException {
		return this.conn.prepareCall(sql, resultSetType, resultSetConcurrency);
	}

	@Override
	public CallableStatement prepareCall(String sql) throws SQLException {
		return this.conn.prepareCall(sql);
	}

	@Override
	public PreparedStatement prepareStatement(String sql, int resultSetType,
			int resultSetConcurrency, int resultSetHoldability)
			throws SQLException {
		return this.conn.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
	}

	@Override
	public PreparedStatement prepareStatement(String sql, int resultSetType,
			int resultSetConcurrency) throws SQLException {
		return this.conn.prepareStatement(sql, resultSetType, resultSetConcurrency);
	}

	@Override
	public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
			throws SQLException {
		return this.conn.prepareStatement(sql, autoGeneratedKeys);
	}

	@Override
	public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
			throws SQLException {
		return this.conn.prepareStatement(sql, columnIndexes);
	}

	@Override
	public PreparedStatement prepareStatement(String sql, String[] columnNames)
			throws SQLException {
		return this.conn.prepareStatement(sql, columnNames);
	}

	@Override
	public PreparedStatement prepareStatement(String sql) throws SQLException {
		return this.conn.prepareStatement(sql);
	}

	@Override
	public void releaseSavepoint(Savepoint savepoint) throws SQLException {
		this.conn.releaseSavepoint(savepoint);
	}

	@Override
	public void rollback() throws SQLException {
		this.conn.rollback();
	}

	@Override
	public void rollback(Savepoint savepoint) throws SQLException {
		this.conn.rollback(savepoint);
	}

	@Override
	public void setAutoCommit(boolean autoCommit) throws SQLException {
		this.conn.setAutoCommit(autoCommit);
	}

	@Override
	public void setCatalog(String catalog) throws SQLException {
		this.conn.setCatalog(catalog);
	}

	@Override
	public void setClientInfo(Properties properties)
			throws SQLClientInfoException {
		this.conn.setClientInfo(properties);
	}

	@Override
	public void setClientInfo(String name, String value)
			throws SQLClientInfoException {
		this.conn.setClientInfo(name, value);
	}

	@Override
	public void setHoldability(int holdability) throws SQLException {
		this.conn.setHoldability(holdability);
	}

	@Override
	public void setReadOnly(boolean readOnly) throws SQLException {
		this.conn.setReadOnly(readOnly);
	}

	@Override
	public Savepoint setSavepoint() throws SQLException {
		return this.conn.setSavepoint();
	}

	@Override
	public Savepoint setSavepoint(String name) throws SQLException {
		return this.conn.setSavepoint(name);
	}

	@Override
	public void setTransactionIsolation(int level) throws SQLException {
		this.conn.setTransactionIsolation(level);
	}

	@Override
	public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
		this.conn.setTypeMap(map);
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		return this.conn.isWrapperFor(iface);
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		return this.conn.unwrap(iface);
	}

	@Override
	public void setSchema(String schema) throws SQLException {
		this.conn.setSchema(schema);
	}

	@Override
	public String getSchema() throws SQLException {
		return this.conn.getSchema();
	}

	@Override
	public void abort(Executor executor) throws SQLException {
		this.conn.abort(executor);
	}

	@Override
	public void setNetworkTimeout(Executor executor, int milliseconds)
			throws SQLException {
		this.conn.setNetworkTimeout(executor, milliseconds);
	}

	@Override
	public int getNetworkTimeout() throws SQLException {
		return this.conn.getNetworkTimeout();
	}

}

           

测试代码:

package  com.my.pool;

import java.sql.Connection;
import java.sql.SQLException;

public class TestMyPool {
	
	public static void main(String[] args) {
		for(int i = 0 ; i < 5 ; i ++){
			new MyThread().start();
		}
	}

}

class MyThread extends Thread{
	@Override
	public void run() {
		try {
			// 获得链接
			Connection conn = MyPoolJdbcUtil.getConnection();
			System.out.println(conn);
			// 归还
			//MyPoolJdbcUtil.closeResource(conn, null, null);
			conn.close(); //本意:真的关闭。期望:将当前链接归还到自定义连接池中 (方法增强)
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

           

测试结果:

数据库连接池--自定义连接池
数据库连接池--自定义连接池