登录 之 服务端响应(四)

2014-11-24 11:36:21 · 作者: · 浏览: 29
new Class[] { Connection.class }, this);
return proxyCon;
}
public Object invoke(Object arg0, Method arg1, Object[] arg2)
throws Throwable {
// TODO Auto-generated method stub
Object obj = null;
if ("close".equals(arg1.getName())) {
pool.releaseConnection(con);
} else {
obj = arg1.invoke(con, arg2);
}
return obj;
}
}
最后实现连接池:ConnectionPool.java
[java]
package com.net;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;
public class ConnectionPool implements ConnectionPoolInterface {
private ReadProperties rp = new ReadProperties();
private static Vector pool;
private static int POOL_MAX_SIZE = 0;
private static ConnectionPool conPool = null;
private static String DRIVER_NAME = "";
private static String URL_BASE = "";
private static String DB_NAME = "";
private static String SERVER_IP = "";
private static int SERVER_PORT = 0;
private static String DB_ADMIN_NAME = "";
private static String DB_ADMIN_PASSWD = "";
ConnectionPool() {
POOL_MAX_SIZE = Integer.parseInt(rp.getProperty("pool_max_size"));
DRIVER_NAME = rp.getProperty("driver_name");
URL_BASE = rp.getProperty("url_base");
DB_NAME = rp.getProperty("db_name");
SERVER_IP = rp.getProperty("server_ip");
SERVER_PORT = Integer.parseInt(rp.getProperty("server_port"));
DB_ADMIN_NAME = rp.getProperty("db_admin_name");
DB_ADMIN_PASSWD = rp.getProperty("db_admin_passwd");
}
public static ConnectionPool getInstance() {
if (conPool == null)
return new ConnectionPool();
else
return conPool;
}
public synchronized Connection getConnection() {
Connection con = null;
try {
if (pool == null)
pool = new Vector();
if (pool.isEmpty()) {
con = ConnectionPool.createConnection();
} else {
int index = pool.size() - 1;
con = pool.get(index);
pool.remove(pool.get(index));
}
} catch (Exception e) {
e.printStackTrace();
}
ConnectionHandler ch = new ConnectionHandler(this);
return ch.bind(con);
}
public synchronized void releaseConnection(Connection con) {
if (pool.size() > POOL_MAX_SIZE) {
try {
if (con != null) {
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
pool.add(con);
}
}
private static Connection createConnection() {
Connection con = null;
try {
Class.forName(DRIVER_NAME);
con = DriverManager.getConnection(URL_BASE + "//" + SERVER_IP + ":"
+ SERVER_PORT + "/" + DB_NAME, DB_ADMIN_NAME, DB_ADMIN_PASSWD);
} catch (ClassNotFoundException CNFex) {
CNFex.printStackTrace();
} catch (SQLException SQLex) {
SQLex.printStackTrace();
}
return con;
}
}