2.自定义连接池的实现

2017-04-03  本文已影响152人  Michael_林

常用的连接池技术包括:DBCP | C3P0,都是十分成熟稳定的连接池技术。本文目的是通过一个自定义的连接池来模仿连接池的实现。
该自定义连接池实现思路:

实现java.sql.Connection接口,实现的部分如下:

import java.sql.Array;
public class ConnectionWarp implements Connection {
private Connection con;
private LinkedList<Connection> pool;

public ConnectionWarp(Connection con){
this.con = con;
}
public ConnectionWarp(Connection con, LinkedList<Connection> pool){
this.con = con;
this.pool = pool;
}
//要加强的方法
@Override
public Statement createStatement() throws SQLException {

  return con.createStatement();

}

@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {

  return con.prepareStatement(sql);

}
@Override
public void close() throws SQLException {
System.out.println("放回连接前:" + pool.size());
pool.addLast(this);
System.out.println("放回连接后;" + pool.size());

  System.out.println("已将连接放回");

}

@Override
public <T> T unwrap(Class<T> iface) throws SQLException {

  return con.unwrap(iface);

}
}

自定义连接池

import java.sql.Connection;
public class MyDataSource {

//1.定义一个连接池
static LinkedList<Connection> pool = new LinkedList<Connection>();

//初始化连接池,放入3个连接
static {
for(int i=0; i<3; i++){
Connection con;
try {
con = JdbcUtils.getConnection();
pool.add(con);
} catch (SQLException e) {

          e.printStackTrace();
      }
  }

}

//获取连接
@SuppressWarnings("resource")
public Connection getConnection(){
if(pool.isEmpty()){
for(int i=0; i<2; i++){
Connection con;
try {
con = JdbcUtils.getConnection();
pool.add(con);
} catch (SQLException e) {

              e.printStackTrace();
          }
      }
  }
  Connection conn = pool.remove();
  ConnectionWarp connWarp = new ConnectionWarp(conn, pool);
  return connWarp;

}

}

上一篇下一篇

猜你喜欢

热点阅读