81,092
社区成员
发帖
与我相关
我的任务
分享
int i = 0;
for (i = 1; i <= connectionsPool.size(); i++) {
if (conn == connectionsPool.get(i-1)) {
break;
}
}
if (i > connectionsPool.size()) {
connectionsPool.addLast(conn);
}
public class MyConnectionHandler implements InvocationHandler {
private int currentCount = 0;
private int maxUseCount = 3;
private MyDataSource2 myDataSource;
private Connection realConnection;
private Connection warpedConnection;
MyConnectionHandler(MyDataSource2 myDataSource) {
this.myDataSource = myDataSource;
}
Connection bind(Connection realConnection) {
this.realConnection = realConnection;
this.warpedConnection = (Connection) Proxy.newProxyInstance(this
.getClass().getClassLoader(), new Class[] { Connection.class },
this);
System.out.println("--" + warpedConnection.getClass().getName());
return warpedConnection;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if ("close".equals(method.getName())) {
this.currentCount++;
if (this.currentCount < this.maxUseCount)
this.myDataSource.free(this.warpedConnection);
else {
this.realConnection.close();
this.myDataSource.setCurrentCount((this.myDataSource
.getCurrentCount() - 1) < 0 ? 0 : (this.myDataSource
.getCurrentCount() - 1));
}
}
return method.invoke(this.realConnection, args);
}
}
public final class MyDataSource2 {
private String url = "jdbc:mysql://localhost:3306/shopping";
private String user = "root";
private String password = "JD-ESMS";
private static int initCount = 4;
private static int maxCount = 6;
private int currentCount = 0;
private static MyDataSource2 myDataSource = new MyDataSource2();
private LinkedList<Connection> connectionsPool = new LinkedList<Connection>();
private MyDataSource2() {
try {
for (int i = 0; i < initCount; i++) {
this.connectionsPool.addLast(this.createConnection());
this.currentCount++;
}
} catch (SQLException e) {
System.err.println("连接池创建失败:");
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
public static MyDataSource2 getInstance() {
return myDataSource;
}
public Connection getConnection() throws SQLException {
synchronized (connectionsPool) {
System.out.print("池内空闲连接数:" + this.connectionsPool.size() + "\t"
+ "当前连接数:" + currentCount + "\t");
if (this.connectionsPool.size() > 0) {
return this.connectionsPool.removeFirst();
}
if (this.currentCount < maxCount) {
currentCount++;
return this.createConnection();
}
throw new SQLException("已达到数据库最大连接数");
}
}
public void free(Connection conn) {
if (!connectionsPool.contains(conn))
connectionsPool.addLast(conn);
}
private Connection createConnection() throws SQLException {
Connection realConnection = DriverManager.getConnection(url, user, password);
MyConnectionHandler proxy = new MyConnectionHandler(this);
return proxy.bind(realConnection);
}
public int getCurrentCount() {
return currentCount;
}
public void setCurrentCount(int currentCount) {
this.currentCount = currentCount;
}
}