zoukankan      html  css  js  c++  java
  • java数据库连接池简单实现

    package cn.lmj.utils;


    import java.io.PrintWriter;
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.LinkedList;
    import javax.sql.DataSource;


    public class JdbcPool implements DataSource

    {

    //选用LinkedList方便移除链接

    public static LinkedList<Connection> list = new LinkedList<Connection>();

    static
    {
    try
    {

    Class.forName("com.mysql.jdbc.Driver");

    //初始化20个链接

    for(int i = 0;i<20;i++)
    {

    final Connection conn = DriverManager.getConnection("jdbc:mysql:///test","root","root");

    //利用jdk动态代理实现增强Connection的close方法

    Connection proxy = (Connection) Proxy.newProxyInstance(JdbcPool.class.getClassLoader(),conn.getClass().getInterfaces(),new InvocationHandler()
    {
    public Object invoke(Object obj, Method m, Object[] arg)
    throws Throwable
    {
    if("close".equals(m.getName()))

    {

    //加到池中供其他线程訪问

    list.addLast(conn);
    }

    return m.invoke(conn,arg);
    }
    });
    list.add(proxy);
    }
    }
    catch (Exception e)
    {
    e.printStackTrace();
    }
    }

    public PrintWriter getLogWriter() throws SQLException
    {
    return null;
    }


    public int getLoginTimeout() throws SQLException
    {
    // TODO Auto-generated method stub
    return 0;
    }


    public void setLogWriter(PrintWriter arg0) throws SQLException
    {
    // TODO Auto-generated method stub

    }


    public void setLoginTimeout(int arg0) throws SQLException
    {
    // TODO Auto-generated method stub

    }


    public boolean isWrapperFor(Class<?> arg0) throws SQLException
    {
    // TODO Auto-generated method stub
    return false;
    }


    public <T> T unwrap(Class<T> arg0) throws SQLException
    {
    // TODO Auto-generated method stub
    return null;
    }


    public Connection getConnection() throws SQLException
    {
    if(list.size()<=0)
    {
    new RuntimeException("数据库忙。稍后再来");
    }

    //移除第一个引用。不能用get,由于get不能移除引用

    return list.removeFirst();
    }


    public Connection getConnection(String arg0, String arg1)
    throws SQLException
    {
    // TODO Auto-generated method stub
    return null;
    }

    }
  • 相关阅读:
    javascript的alert的使用
    UIGestureRecognizer对图像进行缩放、移动、旋转操作
    对开源库使用 AutoCAD 文件格式
    计算机图形学常用算法
    KMP字符串模式匹配详解
    C++面试题String函数实现
    c++虚函数解析
    c++内存分配
    win32编程入门
    C++中Int转换成String
  • 原文地址:https://www.cnblogs.com/clnchanpin/p/6823252.html
Copyright © 2011-2022 走看看