创建数据库连接池:
public class DataSource {
private InputStream inStream;
private Properties pro;
private static int initCount = 5;// 初始连接数
private static int maxCount = 10;// 数据库最大连接数
int currentConnt = 0;// 当前数据库的连接数
LinkedList<Connection> connectionPool=new LinkedList<Connection>();
public DataSource(){
inStream=this.getClass().getResourceAsStream("/system.properties");
pro=new Properties();
try {
pro.load(inStream);
try {
Class.forName(pro.getProperty("driver"));
for(int i=0;i<initCount;i++){
connectionPool.addLast(CreateConnection());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private Connection CreateConnection(){
Connection conn=null;
MyConnectionProxy myproxy=null;
try {
conn=DriverManager.getConnection(pro.getProperty("url"), pro.getProperty("username"), pro.getProperty("password"));
myproxy=new MyConnectionProxy(this);
} catch (SQLException e) {
e.printStackTrace();
}
currentConnt++;
return myproxy.bind(conn);
}
public Connection GetConnection(){
synchronized (connectionPool) {
if(connectionPool.size()>0){
return connectionPool.removeFirst();
}
if(currentConnt<maxCount){
return CreateConnection();
}
throw new RuntimeException("数据库已达到最大连接数!");
}
}
}
创建代理类
public class MyConnectionProxy implements InvocationHandler {
private Connection realConnection;
private Connection proxyConnection;
private DataSource datasource;
private int maxUseCount = 10;
private int currentUserCount = 0;
MyConnectionProxy(DataSource ds){
this.datasource=ds;
}
Connection bind(Connection conn){
this.realConnection=conn;
proxyConnection=(Connection)Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{Connection.class}, this);
//Proxy.newProxyInstance()方法表示:产生一个新的类,该类继承于第二个参数Connnection,但该类的方法的现实是由第三个参数this负责实现
return proxyConnection;
}
//MyConnectionProxy类所有方法的实现都是由invoke方法实现
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if(method.getName().equals("close")){
this.currentUserCount++;
if(this.currentUserCount<maxUseCount){
this.datasource.connectionPool.addLast(this.proxyConnection);
}else{
this.realConnection.close();
this.datasource.currentConnt--;
}
}
return method.invoke(this.realConnection, args);
}
}
JDBC工具类:
public class SQLDBConnection {
private static SQLDBConnection sqldb;
private DataSource datasource;
private SQLDBConnection(){
datasource=new DataSource();
}
public static SQLDBConnection getSQLDBConnection(){
if(sqldb==null){
synchronized (SQLDBConnection.class) {
if(sqldb==null){
sqldb=new SQLDBConnection();
}
}
}
return sqldb;
}
public Connection GetConnection(){
return this.datasource.GetConnection();
}
public