proxy代理對鏈接Connection的處理
阿新 • • 發佈:2017-05-11
tco gin ins reat eth lis 創建 org get
package com.pool.cn; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.SQLException; import java.util.LinkedList; import org.junit.Test; import com.utils.cn.JDBCUtils; /**
*這裏是主要代碼
**/ public classConnPoolTest { private int init_count = 3;//連接池的初始值 private int max_count = 6;//提供鏈接的最大值 private int convert_count = 0;//鏈接的當前值 LinkedList<Connection> list = new LinkedList<Connection>(); // 創建連接 public Connection createConnection() { Connection connection = JDBCUtils.getConnection(); Connection proxycloseConnection= proxyCloseConnection(connection); return proxycloseConnection; } // 網鏈接池中添加連接 public void connPool() { if (convert_count < init_count) { for (int i = 0; i < init_count; i++) { list.add(createConnection()); } } }// 請求使用連接 public Connection getConnection() { // 如果連接池中有 if (list.size() > 0) { convert_count++; return list.removeFirst(); } // 如果連接池沒有,但是小於最大連接數 if (convert_count < max_count) { convert_count++; return createConnection(); } // 如果超出了最大連接數還在請求,拋出異常 throw new RuntimeException("已經拿到最大連接數"); } // 釋放連接 public void relaceseConnection(Connection connection) { // 如果連接數小於小於初始化的數目則放回連接池中 if (list.size() < init_count) { convert_count--; list.add(connection); } else { try { connection.close(); convert_count--; } catch (SQLException e) { // TODO Auto-generated catch block throw new RuntimeException(e); } } } // 使用代理,來監聽Connection中的方法 public Connection proxyCloseConnection(Connection connection) { Connection proxy = (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class[] { Connection.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; String name = method.getName(); if ("close".equals(name)) { System.out.println("begin:close執行"); list.addLast(connection); System.out.println("end:放入連接池"); } else { result = method.invoke(connection, args); } return result; } }); return proxy; } @Test public void testName() throws Exception { connPool(); Connection connection1 = getConnection(); getConnection(); getConnection(); getConnection(); getConnection(); getConnection(); // relaceseConnection(connection1); connection1.close(); getConnection(); System.out.println("連接池中剩余的連接數:" + list.size()); System.out.println("連接池中的連接數:" + convert_count); } }
proxy代理對鏈接Connection的處理