java实现数据库连接池

java实现数据库连接池:新建X个连接放到LinkedList中,销毁时,放回linkedList
package com.whaty.platform.sso.util;
import com.whaty.platform.util.Const;

import javax.sql.DataSource;
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 java.util.Properties;
/**
 * Created by zhangluyao on 2018/5/28.
 * 编写数据库连接池
 */

public class SyyOraclePool implements DataSource{

    /**
     * @Field: listConnections
     *         使用LinkedList集合来存放数据库链接,
     *        由于要频繁读写List集合,所以这里使用LinkedList存储数据库连接比较合适
     */
    private static LinkedList<Connection> listConnections = new LinkedList<Connection>();

    static{
        //在静态代码块中加载db.properties数据库配置文件
        Properties properties= Const.getProperty("init.properties");
        try {
            String driver = properties.getProperty("syy.datasource.driverClassName");
            String url = properties.getProperty("syy.datasource.url");
            String username = properties.getProperty("syy.datasource.username");
            String password = properties.getProperty("syy.datasource.password");
            //数据库连接池的初始化连接数大小
            int jdbcPoolInitSize =Integer.parseInt(properties.getProperty("c3p0.initialPoolSize"));
            //加载数据库驱动
            Class.forName(driver);
            for (int i = 0; i < jdbcPoolInitSize; i++) {
                Connection conn = DriverManager.getConnection(url, username, password);
                System.out.println("获取到了链接" + conn);
                //将获取到的数据库连接加入到listConnections集合中,listConnections集合此时就是一个存放了数据库连接的连接池
                listConnections.add(conn);
            }

        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }

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

    }

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

    }

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

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

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

    /* 获取数据库连接
     * @see javax.sql.DataSource#getConnection()
     */
    @Override
    public Connection getConnection() throws SQLException {
        //如果数据库连接池中的连接对象的个数大于0
        if (listConnections.size()>0) {
            //从listConnections集合中获取一个数据库连接
            final Connection conn = listConnections.removeFirst();
            System.out.println("listConnections数据库连接池大小是" + listConnections.size());
            //返回Connection对象的代理对象
            return (Connection) Proxy.newProxyInstance(SyyOraclePool.class.getClassLoader(), new Class[] { Connection.class }, new InvocationHandler(){
                @Override
                public Object invoke(Object proxy, Method method, Object[] args)
                        throws Throwable {
                    if(!method.getName().equals("close")){
                        return method.invoke(conn, args);
                    }else{
                        //如果调用的是Connection对象的close方法,就把conn还给数据库连接池
                        listConnections.add(conn);
                        System.out.println(conn + "被还给listConnections数据库连接池了!!");
                        System.out.println("listConnections数据库连接池大小为" + listConnections.size());
                        return null;
                    }
                }
            });
        }else {
            throw new RuntimeException("对不起,数据库忙");
        }
    }

    @Override
    public Connection getConnection(String username, String password)
            throws SQLException {
        return null;
    }
}
工具类,获得conn,销毁方法
package com.whaty.platform.sso.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


/**
 * Created by zhangluyao on 2017/10/18.
 */
public class DataConn {

        /**
         * @Field: pool
         *          数据库连接池
         */
        private static SyyOraclePool pool = new SyyOraclePool();

        /**
         * @Method: getConnection
         * @Description: 从数据库连接池中获取数据库连接对象
         * @Anthor:zly
         * @return Connection数据库连接对象
         * @throws SQLException
         */
        public static Connection getConnection() throws SQLException{
            return pool.getConnection();
        }

        /**
         * @Method: release
         * @Description: 释放资源,
         * 释放的资源包括Connection数据库连接对象,负责执行SQL命令的Statement对象,存储查询结果的ResultSet对象
         * @Anthor:孤傲苍狼
         *
         * @param conn
         * @param st
         * @param rs
         */
        public static void release(Connection conn,Statement st,ResultSet rs){
            if(rs!=null){
                try{
                    //关闭存储查询结果的ResultSet对象
                    rs.close();
                }catch (Exception e) {
                    e.printStackTrace();
                }
                rs = null;
            }
            if(st!=null){
                try{
                    //关闭负责执行SQL命令的Statement对象
                    st.close();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if(conn!=null){
                try{
                    //关闭Connection数据库连接对象
                    conn.close();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值