数据库连接池的简单实现

数据库连接池的简单实现

package com.roy.pool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Authror royLuo
 * @Date 2020/2/29 15:50
 **/
public class PoolConnection implements MyPoolConnection {

     Lock lock = new ReentrantLock();
     Condition a =lock.newCondition();
    //定义一个装线程的集合
     List<Connection> activeConnection =  new CopyOnWriteArrayList<Connection>(); //记录活跃数
     List<Connection> freeConnection = new CopyOnWriteArrayList<>();//记录空闲数
    //定义一个计数器计算创建的线
     AtomicInteger cout ;

     public PoolConnection(){
         //初始化
       cout = new AtomicInteger(0);
       init();
     }

     //初始化一定数量的空间连接
     private void init(){
         for (int i =0;i<Integer.parseInt(PropertiesUtils.map.getProperty("initConnections"));i++){
             Connection connection = newConnection();
             if(connection!=null){
                 freeConnection.add(connection);
             }
         }
     }

     //返回用户连接
    @Override
    public  Connection getConnetion() {
         lock.lock();
        Connection connection = null ;
        //判断是否达到最大连接数---》给用户连接还是等待。
        try {
            if (cout.get() < Integer.valueOf(PropertiesUtils.map.getProperty("maxConnections"))) {
                if (freeConnection.size() > 0) { //表示还有连接没事干
                    connection = freeConnection.remove(0);
                } else {//表示大家都在忙,需要添加帮手
                    connection = newConnection();
                }
                //判断这个新帮手是否能工作
                if (isAvaliable(connection)) {//能帮手
                    //判断从空间线程获取的和新创建的线程能用
                    //添加都活跃线程里面
                    activeConnection.add(connection);
                } else {
                    cout.decrementAndGet();
                    getConnetion();
                }
            } else { //已达到上限只能让它等待了
                  a.await(Integer.parseInt(PropertiesUtils.map.getProperty("connTimeOut")), TimeUnit.SECONDS);
//                try {
//                    wait(Integer.parseInt(PropertiesUtils.map.getProperty("connTimeOut")));
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
             lock.unlock();
        }
         return connection;
    }

    //释放连接
    @Override
    public  void releaseConnetion(Connection connection) {
         lock.lock();
         //判断连接是否可用
        try {
            if (isAvaliable(connection)) {
                //判断空闲池是否满
                if (freeConnection.size() < Integer.valueOf(PropertiesUtils.map.getProperty("maxConnections"))) {
                    freeConnection.add(connection);
                } else {//满了释放连接
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                //从活跃集合移除当前这个连接
                activeConnection.remove(connection);
                cout.decrementAndGet();
                //唤醒其他线程
                a.signalAll();
            } else {//不可用
                throw new RuntimeException("连接回收异常");
            }
        }catch (Exception e){
              e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }



     //创建连接
    public Connection newConnection(){
        try {
            //加载驱动
            Class.forName(PropertiesUtils.map.getProperty("driverName"));
            Connection connection = DriverManager.getConnection(PropertiesUtils.map.getProperty("url"), PropertiesUtils.map.getProperty("userName"), PropertiesUtils.map.getProperty("password"));
            cout.addAndGet(1);
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
            return  null;
        }
    }

    //判断是否可用
    public boolean isAvaliable(Connection connection){
        try {
            if(null==connection||connection.isClosed());
            return  false;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  true;
    }

}

# 数据库相关
driverName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
userName=root
password=root

# 空闲池的 最小数
minConnections=1
# 空闲池的 最大数
maxConnections=10
# 初始化的连接数
initConnections=5

# 本次连接超时时间(重试时间)
connTimeOut=1000
# 最大的连接数
maxActiveConnetions=10
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值