在上一篇博客中,主要涉及到了java中基本的对于mySql的访问,以及简单的封装。在实际的运用中,对于各个连接的建立与释放也是非常消耗资源的,所以在本篇博客中主要涉及自定义连接池的内容。
- 简单的自定义连接池
代码如下
public class CustomPool {
private static String url = "jdbc:mysql://localhost:3306/test_jdbc";
private static String user = "";//连接数据库的用户名
private static String password = "";//连接数据库的密码
//创建容器,用于存放Connection对象
private static LinkedList<Connection> pool = new LinkedList<Connection>();
//在静态代码块中,初始化连接池中的连接
static {
try {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
for (int i = 0; i < 3; i++) {
//获得连接
Connection conn = DriverManager.getConnection(url, user, password);
//将连接添加到连接池中
pool.add(conn);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获得连接
*/
public static Connection getConnection() {
try {
//如果池中还有连接,则返回一个连接
if (!pool.isEmpty()) {
Connection conn = pool.removeFirst();
return conn;
}
} catch (Exception e) {
e.printStackTrace();
}
//如果没有,则返回null
return null;
}
/**
* 释放资源
* 归还连接
*/
public static void release(Connection conn, PreparedStatement ps, ResultSet rs) {
try {
if (rs != null){
rs.close();
}
} catch (Exception e) {
}
try {
if (ps != null){
ps.close();
}
}catch (Exception e){
}
try {
//归还到连接池中
if (conn != null) {
pool.add(conn);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 自定义连接池的方法增强
在前一部分的自定义连接池中,如果用户未使用release()方法,而使用了conn.close()方法,则任然会将连接进行释放,所以在这一部分中,我们将重写Connection接口,使其调用close()方法时不会释放资源,而是向自定义的连接池中归还连接
以下是代码
public class MyConnection implements Connection{
private Connection conn;
private List<Connection> pool;
public MyConnection(Connection conn, List<Connection> pool){
this.conn = conn;
this.pool = pool;
}
/**
* 对close()方法进行修改,使其变为归还连接
*/
@Override
public void close() throws SQLException {
pool.add(conn);
}
//同时对prepareStatement()方法进行修改
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return conn.prepareStatement(sql);
}
//此接口中还有许多方法,但都不需要做出修改
...
}
此时在CustomPool类中,需要修改三处
public class CustomPool {
...
Connection conn = DriverManager.getConnection(url, user, password);
//获得自定义的连接
MyConnection myConn = new MyConnection(conn, pool);
//将自定义的连接添加到连接池中
pool.add(myConn);
...
}
/**
* 获得连接
*/
public static MyConnection getConnection() {
...
//如果池中还有连接,则返回一个连接
if (!pool.isEmpty()) {
MyConnection conn = (MyConnection) pool.removeFirst();
return conn;
}
...
}
/**
* 释放资源
* 归还连接
*/
public static void release(Connection conn, PreparedStatement ps, ResultSet rs) {
...
//此时调用的是MyConnection中的close()方法
//将连接归还到连接池中
if (conn != null) {
conn.close();
}
...
}
public class Test {
public static void main(String[] args) {
//将此处的Connection更换为MyConnection
MyConnection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = CustomPool.getConnection();
String sql = "select * from table_user_info where userID=?";
ps = conn.prepareStatement(sql);
ps.setString(1,"A001");
rs = ps.executeQuery();
while (rs.next()){
System.out.println(rs.getString("userName"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
CustomPool.release(conn, ps, rs);
}
}
}