proxy代理对链接Connection的处理

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 class ConnPoolTest { 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); } }
原文地址:https://www.cnblogs.com/ShaoXin/p/6839748.html