/**
* 用静态工厂方法管理一个唯一的可重用的连接
*/
public class ConnUtils {
private ConnUtils(){}
private static Connection con;
//在静态代码块中创建与数据库的连接
static{
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql:///db_test?characterEncoding=UTf8";
con = DriverManager.getConnection(url,"root","root");
}catch(Exception e){
throw new RuntimeException(e.getMessage(),e);
}
}
//使用静态工厂方法,返回connection实例
public static Connection getCon(){[W1]
return con;
}
}
public class ConnUtils2 {
//声明一个容器,放所有声明的连接Connection
private static List<Connection> pool = new ArrayList<Connection>();
static{
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql:///db_test?characterEncoding=UTf8";
for(int i=0;i<3;i++){
//创建三个连接
Connection con = DriverManager.getConnection(url,"root","root");
//将这个三个连接放到pool中去
pool.add(con);
}
System.err.println("连接:"+pool);
}catch(Exception e){
throw new RuntimeException(e.getMessage(),e);
}
}
public static Connection getCon(){
synchronized (pool) {
Connection con = pool.remove(0);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println("还有:"+pool.size());
return con;
}
}
//手工还连接 – close
public static void back(Connection con){
System.err.println("还连接:"+con);
pool.add(con);
}
}
public class ConnUtils3 {
//声明连接池维护所有的连接
private static List<Connection> pool = new ArrayList<Connection>();
//静态代码块中创建多个连接
static{
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql:///db_test?characterEncoding=UTF8";
for(int i=0;i<3;i++){
final Connection con = DriverManager.getConnection(url,"root","root");
//对con对象进行动态代理
Object proxyedCon =
Proxy.newProxyInstance(
ConnUtils3.class.getClassLoader(),
new Class[]{Connection.class},
//声明执行句柄,只对close方法设置拦截
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
if(method.getName().equals("close")){
System.err.println("想关闭连接,不能关,还连接");
//将proxy再加到pool中,这个proxy就是proxyedCon
synchronized (pool) {
pool.add((Connection) proxy);
pool.notify();
}
return null;
}else{
System.err.println("放行"+method.getName());
return method.invoke(con, args); // 通过反射执行被代理对象的方法
}
}
});
//将代理对象添加到池中
pool.add((Connection) proxyedCon);
}
}catch(Exception e){
throw new RuntimeException(e.getMessage(),e);
}
}
/**
* 提供一个静态工厂方法返回一个连接
*/
public static Connection getCon(){
synchronized (pool) {
if(pool.size()==0){
try {
pool.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
return getCon();
}
Connection con = pool.remove(0);//返回一个代理的connection对象
System.err.println("还有几个:"+pool.size());
return con;
}
}
}Author:顾故
Sign:别输给曾经的自己
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/lzgs_4/article/details/47092121