为什么要有连接池呢??
因为在数据连接中一个连接的启用和关闭是非常耗费时间的,导致效率不高,所以在实际应用中,我们会创建连接池来提升效率。
先写一个简单自己实现的连接池类,这个不需要编写装饰的connection,但是不规范。
package com.itheima.pool;
import java.sql.Connection;
import java.util.Collections;
import java.util.LinkedList;
import com.itheima.util.DBUtils;
//模拟数据库连接池,但不具备实际开发意义
public class SimpleConnectionPool {
//创建一个存放连接的池子
private static LinkedList<Connection> pool = (LinkedList<Connection>) Collections.synchronizedList(new LinkedList<Connection>());
static{
try {
for (int i = 0; i < 10; i++) {
Connection conn = DBUtils.getConnection();
pool.add(conn);
}
} catch (Exception e) {
throw new ExceptionInInitializerError("初始化数据库连接失败,请检查配置文件是否正确!");
}
}
//得到一个连接
public static Connection getConnectionFromPool(){
Connection conn = null;
if(pool.size()>0){
conn = pool.removeFirst();//从池中取出一个连接
return conn;
}else{
//等待
//新创建一个连接
throw new RuntimeException("服务器忙。。。");
}
}
//释放资源
public static void release(Connection conn){
pool.addLast(conn);
}
}
然后在通过一个实现datasource接口
package com.itheima.datasource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.LinkedList;
import javax.sql.DataSource;
import com.itheima.util.DBUtils;
public class MyDataSource implements DataSource{
//创建一个存放连接的池子
private static LinkedList<Connection> pool = (LinkedList<Connection>) Collections.synchronizedList(new LinkedList<Connection>());
static{
try {
for (int i = 0; i < 10; i++) {
Connection conn = DBUtils.getConnection();
pool.add(conn);
}
} catch (Exception e) {
throw new ExceptionInInitializerError("初始化数据库连接失败,请检查配置文件是否正确!");
}
}
public Connection getConnection() throws SQLException {
Connection conn = null;
if(pool.size()>0){
conn = pool.removeFirst();//从池中取出一个连接
MyConnection myConn = new MyConnection(conn,pool);//得到一个包装后的MyConnection对象
return myConn;
}else{
//等待
//新创建一个连接
throw new RuntimeException("服务器忙。。。");
}
}
public Connection getConnection(String username, String password)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public void setLogWriter(PrintWriter out) throws SQLException {
// TODO Auto-generated method stub
}
public void setLoginTimeout(int seconds) throws SQLException {
// TODO Auto-generated method stub
}
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
}
因为close方法会把connection关闭,这样导致连接池里面的连接数会变少,所以要写一个自己装饰过的connction类,重写close方法;
package com.itheima.datasource;
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.LinkedList;
import java.util.Map;
import java.util.Properties;
//1、编写一个类,实现与被包装类相同的接口。(具备相同的行为)
//2、定义一个被包装类类型的变量。
//3、定义构造方法,把被包装类的对象注入,给被包装类变量赋值。
//4、对于不需要改写的方法,调用原有的方法。
//5、对于需要改写的方法,写自己的代码
public class MyConnection implements Connection{
private Connection oldConnection;//com.mysql.jdbc.Connection
private LinkedList<Connection> pool;//连接池对象
public MyConnection(Connection oldConnection,LinkedList<Connection> pool){
this.oldConnection = oldConnection;//得到com.mysql.jdbc.Connection
this.pool = pool;//得到连接池对象
}
public void close() throws SQLException {
pool.addLast(oldConnection);
}
public PreparedStatement prepareStatement(String sql) throws SQLException {
return oldConnection.prepareStatement(sql);
}
public <T> T unwrap(Class<T> iface) throws SQLException {
return oldConnection.unwrap(iface);
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return oldConnection.isWrapperFor(iface);
}
public Statement createStatement() throws SQLException {
return oldConnection.createStatement();
}
public CallableStatement prepareCall(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
}
public String nativeSQL(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
}
public void setAutoCommit(boolean autoCommit) throws SQLException {
// TODO Auto-generated method stub
}
public boolean getAutoCommit() throws SQLException {
// TODO Auto-generated method stub
return false;
}
public void commit() throws SQLException {
// TODO Auto-generated method stub
}
public void rollback() throws SQLException {
// TODO Auto-generated method stub
}
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
return false;
}
public DatabaseMetaData getMetaData() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public void setReadOnly(boolean readOnly) throws SQLException {
// TODO Auto-generated method stub
}
public boolean isReadOnly() throws SQLException {
// TODO Auto-generated method stub
return false;
}
public void setCatalog(String catalog) throws SQLException {
// TODO Auto-generated method stub
}
public String getCatalog() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public void setTransactionIsolation(int level) throws SQLException {
// TODO Auto-generated method stub
}
public int getTransactionIsolation() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
public SQLWarning getWarnings() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public void clearWarnings() throws SQLException {
// TODO Auto-generated method stub
}
public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
// TODO Auto-generated method stub
return null;
}
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
// TODO Auto-generated method stub
return null;
}
public Map<String, Class<?>> getTypeMap() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
// TODO Auto-generated method stub
}
public void setHoldability(int holdability) throws SQLException {
// TODO Auto-generated method stub
}
public int getHoldability() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
public Savepoint setSavepoint() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public Savepoint setSavepoint(String name) throws SQLException {
// TODO Auto-generated method stub
return null;
}
public void rollback(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub
}
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub
}
public Statement createStatement(int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public PreparedStatement prepareStatement(String sql, String[] columnNames)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public Clob createClob() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public Blob createBlob() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public NClob createNClob() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public SQLXML createSQLXML() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public boolean isValid(int timeout) throws SQLException {
// TODO Auto-generated method stub
return false;
}
public void setClientInfo(String name, String value)
throws SQLClientInfoException {
// TODO Auto-generated method stub
}
public void setClientInfo(Properties properties)
throws SQLClientInfoException {
// TODO Auto-generated method stub
}
public String getClientInfo(String name) throws SQLException {
// TODO Auto-generated method stub
return null;
}
public Properties getClientInfo() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public Array createArrayOf(String typeName, Object[] elements)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public Struct createStruct(String typeName, Object[] attributes)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
}
终极版,把装饰类细化的更清楚
package com.itheima.warper;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.LinkedList;
import javax.sql.DataSource;
import com.itheima.util.DBUtils;
public class MyDataSource implements DataSource{
//创建一个存放连接的池子
private static LinkedList<Connection> pool = (LinkedList<Connection>) Collections.synchronizedList(new LinkedList<Connection>());
static{
try {
for (int i = 0; i < 10; i++) {
Connection conn = DBUtils.getConnection();
pool.add(conn);
}
} catch (Exception e) {
throw new ExceptionInInitializerError("初始化数据库连接失败,请检查配置文件是否正确!");
}
}
public Connection getConnection() throws SQLException {
Connection conn = null;
if(pool.size()>0){
conn = pool.removeFirst();//从池中取出一个连接
MyConnection myConn = new MyConnection(conn,pool);//得到一个包装后的MyConnection对象
return myConn;
}else{
//等待
//新创建一个连接
throw new RuntimeException("服务器忙。。。");
}
}
public Connection getConnection(String username, String password)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public void setLogWriter(PrintWriter out) throws SQLException {
// TODO Auto-generated method stub
}
public void setLoginTimeout(int seconds) throws SQLException {
// TODO Auto-generated method stub
}
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
}
package com.itheima.warper;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedList;
public class MyConnection extends MyConnectionWarper {
private Connection oldConn;
private LinkedList<Connection> pool;
public MyConnection(Connection oldConn,LinkedList<Connection> pool) {
super(oldConn);
this.oldConn = oldConn;
this.pool = pool;
}
@Override
public void close() throws SQLException {
pool.addLast(oldConn);
}
}
浙公网安备 33010602011771号