自定义连接池实现

来源:互联网 发布:2018软件工程硕士在职 编辑:程序博客网 时间:2024/05/22 21:02

直接上代码...

自定义连接类:JdbcUtil

/** *  *  (1) 线程池解决的核心问题 : 如何获得多个连接?  如何回收连接, 是连接重用? *  (2) 由于线程线程的并发性质, 需要同步获取连接代码块. *  (3) 既然我们不能关闭连接, 但是我们又习惯与关闭连接. 通过代理对connection 的 close()进行重写. * */public class JdbcUtil {// 连接缓存池对象private static LinkedList<Connection> connectionPool = new LinkedList<Connection>();private static String driver;private static String url; private static String password;private static String user;static {// 从配置文件中获取连接信息Properties properties = new Properties();try {properties.load(JdbcUtil3.class.getClassLoader().getResourceAsStream("jdbc.properties"));} catch (IOException e1) {e1.printStackTrace();}driver = properties.getProperty("driver");url = properties.getProperty("url");password = properties.getProperty("password");user = properties.getProperty("user");// 注册驱动try {Class.forName(driver);} catch (ClassNotFoundException e) {e.printStackTrace();}// 循环获得代理连接对象, 并放入缓存中for(int i = 0; i < 3; i++){try {// 获得连接final Connection connection = DriverManager.getConnection(url, user, password);// 获得连接代理对象Object proxy = Proxy.newProxyInstance(JdbcUtil3.class.getClassLoader(), // 用于加载动态生成的字节码new Class[]{Connection.class}, // 用于生成的类接口new InvocationHandler(){ //调用句柄 == 方法的实现 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {if(method.getName().equals("close")){ //对close()方法进行过滤代理synchronized (connectionPool) {// 这里的proxy 就是this的意思, 代表代理对象connectionPool.addLast((Connection)proxy);// 通知线程等待池connectionPool.notify();return null;}} else {return (Object)method.invoke(connection, args);}}});// 向缓存池中添加连接代理对象connectionPool.add((Connection)proxy);} catch (SQLException e) {e.printStackTrace();}}}public static  Connection getConnection(){// 当多线程并发访问的时候, 需要对象锁机制来控制原子性操作synchronized (connectionPool) {if(connectionPool.size() <= 0){try {connectionPool.wait();} catch (InterruptedException e) {e.printStackTrace();}return getConnection(); // 再次判断, 获取, 也可以通过while()循环进行判断}// 向缓存池中移除,并返回连接对<span style="font-size:12px;">象</span>return connectionPool.removeFirst();}}}

测试类:JdbcUtilTest

<span style="font-size:12px;">public class JdbcUtilTest {// 测试多个线程获得连接@Testpublic void testGetConnection() throws Exception {for(int i = 0; i < 50; i++){Runnable run = new Runnable(){public void run() {Connection connection = JdbcUtil.getConnection();System.out.println(connection);try {connection.close();} catch (SQLException e) {e.printStackTrace();}}};new Thread(run).start();}}}</span>

数据库配置文件:jdbc.properties

#路径:src/jdbc.properties文件内容driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/testpassword=123456user=root



0 0
原创粉丝点击