封装简易版数据库连接池

初衷

最近在公司项目在接入华为的CarBonData,但与已开源的CarBon还多多少少有一些区别,并且集群环境加的还有KERBEROS认证,捣鼓了一天头发都愁掉了也没能用SparkSession成功连通。无奈之下只能选择JDBC通过Spark Thrift Server连接,使用JDBC连接时没有问题,以往写JDBC时操作完数据库后都会将连接关闭,下次请求时在创建,原本是没有什么问题,但是每次KERBEROS认证加上创建数据库连接特别耗时直接影响了程序响应,于是便有了下面的简易版连接池,刚好最近没时间写东西,就用这个水一篇吧。

简单思路

根据初始配置,创建一定数量的连接,存放在对象池中,并提供获取连接方法getConnection。使用时判断当前已连接数是否小于最大活跃连接数大于等待连接释放再次获取,小于则继续判断是否有空闲连接,有则获取返回,无则创建返回。连接使用完后调用releaseConnection回收或关闭连接。

下面就直接上代码吧,就不逐行解释了,代码中打的也都有注释

public class CarBonDbConfig {
    /**
     * 连接驱动
     */
    private String driver;
    /**
     * 连接地址
     */
    private String url;
    /**
     * 空闲连接池,最小连接数,默认为2
     */
    private final Integer MIN_FREE_CONNECTIONS = 2;
    private Integer minFreeConnections = MIN_FREE_CONNECTIONS;
    /**
     * 空闲连接池,最大连接数,默认为8
     */
    private final static Integer MAX_FREE_CONNECTIONS = 8;
    private Integer maxFreeConnections = MAX_FREE_CONNECTIONS;
    /**
     * 活跃连接池,最大连接数,默认为8
     */
    private final Integer MAX_ACTIVE_CONNECTIONS = 8;
    private Integer maxActiveConnection = MAX_ACTIVE_CONNECTIONS;
    /**
     * 初始化连接数,默认为2个
     */
    private final Integer INIT_CONNECTIONS = 2;
    private Integer initConnections = INIT_CONNECTIONS;
    /**
     * 连接超时时间,默认为20分钟
     */
    private final Long CONNECTION_TIME_OUT = 1000*60*20L;
    private Long connectionTimeOut = CONNECTION_TIME_OUT;
    /**
     * 自检循环时间,默认为60秒
     */
    private final Long RECHECK_TIME = 1000*60L;
    private Long recheckTime = RECHECK_TIME;

    get.....忽略
    set.....忽略

}

public class ConnectionPool {
    /**
     * 空闲连接池
     */
    private CopyOnWriteArrayList<Connection> freePool=new CopyOnWriteArrayList<Connection>();
    /**
     * 活跃连接池
     */
    private CopyOnWriteArrayList<Connection> activePool=new CopyOnWriteArrayList<Connection>();
    /**
     * 连接池配置
     */
    private CarBonDbConfig dbConfig;
    /**
     * 记录已创建的连接数
     */
    private AtomicInteger countConnection=new AtomicInteger();
    public ConnectionPool(CarBonDbConfig dbConfig) {
        this.dbConfig=dbConfig;
        try {
            Class.forName(dbConfig.getDriver());
            //1. 初始化连接池
            for(int i=0;i<dbConfig.getInitConnections();i++) {
                Connection connection=newConnection();
                if(connection!=null) {
                    freePool.add(connection);
                }
            }
            //2.新开一线程,启动自检机制
            new Thread(()->{
                recheckConnection();
            }).start();
        } catch (ClassNotFoundException e) {
            throw new ConnectionPoolException(ConnectionEnum.DRIVER_NOT_FOUND);
        }
    }

    /**
     * @Author lijiale
     * @MethodName newConnection
     * @Description 创建新连接
     * @Date 15:02 2021/3/30
     * @Version 1.0
     * @param
     * @return: java.sql.Connection
    **/
    private synchronized Connection newConnection() {
        Connection connection=null;
        try {
            connection=DriverManager.getConnection(dbConfig.getUrl());
            countConnection.incrementAndGet();
        } catch (SQLException e) {
            throw new ConnectionPoolException(ConnectionEnum.CONNECTION_FAIL);
        }
        return connection;
    }

    /**
     * @Author lijiale
     * @MethodName isAlive
     * @Description 判断连接是否可用
     * @Date 15:03 2021/3/30
     * @Version 1.0
     * @param connection
     * @return: boolean
    **/
    private boolean isAlive(Connection connection) {
        try {
            if(connection==null||connection.isClosed()) {
                return false;
            }
        } catch (SQLException e) {
            throw new ConnectionPoolException(ConnectionEnum.CONNECTION_STATUS_ERROE);
        }
        return true;
    }

    /**
     * @Author lijiale
     * @MethodName recheckConnection
     * @Description 检查当前连接数是否低于最低线程数,是则创建新线程
     * @Date 15:03 2021/3/30
     * @Version 1.0
     * @param
     * @return: void
    **/
    private synchronized void recheckConnection() {
        //1.检查所有空闲连接是否可用,不可用的直接关闭连接
        //使用迭代器来进行数据的遍历删除,避免快速迭代失败
        Iterator<Connection> it=freePool.iterator();
        while(it.hasNext()) {
            if(!isAlive(it.next())) {
                it.remove();
            }
        }
        //2.检查当前连接数是否满足最低空闲连接数,若低于最小空闲数,新增连接放入空闲池
        final int count=countConnection.get();
        if(count<dbConfig.getMinFreeConnections()) {
            for(int i=count;i<2;i++) {
                Connection connection=newConnection();
                if(connection!=null) {
                    freePool.add(connection);
                }
            }
        }
        try {
            long start=System.currentTimeMillis();
            while(System.currentTimeMillis()-start<dbConfig.getRecheckTime()) {
                wait(dbConfig.getRecheckTime());
            }
            recheckConnection();
        } catch (InterruptedException e) {
            throw new ConnectionPoolException(ConnectionEnum.INTERRUPT_ERROR);
        }
    }

    /**
     * @Author lijiale
     * @MethodName getConnection
     * @Description 从连接池中获取连接
     * @Date 15:03 2021/3/30
     * @Version 1.0
     * @param
     * @return: java.sql.Connection
    **/
    public synchronized Connection getConnection() {
        Connection connection=null;
        //1. 判断当前已连接数是否小于最大活跃连接数
        if(activePool.size()<dbConfig.getMaxActiveConnection()) {
            //2.如果空闲连接池里存在连接,拿出连接
            if(freePool.size()>0) {
                connection=freePool.remove(0);
            }else {
                //3.空闲连接不够,创建新连接
                connection=newConnection();
            }
            if(isAlive(connection)) {
                activePool.add(connection);
            }
        }else {
            //4.活跃连接池内连接数已满,阻塞线程,等待唤醒
            try {
                wait(dbConfig.getConnectionTimeOut());
            } catch (InterruptedException e) {
                throw new ConnectionPoolException(ConnectionEnum.INTERRUPT_ERROR);
            }
            return getConnection();
        }
        return connection;
    }

    /**
     * @Author lijiale
     * @MethodName releaseConnection
     * @Description 释放连接
     * @Date 15:50 2021/3/30
     * @Version 1.0
     * @param connection
     * @return: boolean
    **/
    public synchronized boolean releaseConnection(Connection connection) {
        //1.判断连接是否可用
        if(isAlive(connection)) {
            //2.判断空闲池是否已满
            if(freePool.size()<dbConfig.getMaxFreeConnections()) {
                //未满,回收连接
                freePool.add(connection);
            }else {
                //已满,关闭连接并减少连接计数
                try {
                    countConnection.decrementAndGet();
                    connection.close();
                } catch (SQLException e) {
                    throw new ConnectionPoolException(ConnectionEnum.CONNECTION_CLOSE_FAIL);
                }
            }
            //3.从活跃池中移除连接
            activePool.remove(connection);
            //4.唤醒所有被阻塞的线程
            notifyAll();
            return true;
        }
        return false;
    }
}

单例的管理类,这个可以忽略的,因为我这边在创建连接前需要做KERBEROS认证,然后再获取集群信息创建连接所以才加了这个,其实这个池子完全可以参考之前写一篇帖子 手写starter. 将其封装成starter

public class CarBonDbPoolManager {
    private static class Builder{
        //1.加载jdbc配置文件,配置连接池信息
        private static CarBonDbConfig dbConfig=null;
        static{
            try {
                KerberosAuth.authKerberos();
            } catch (IOException e) {
                e.printStackTrace();
            }
            dbConfig=new CarBonDbConfig();
            dbConfig.setUrl(KerberosAuth.globalURL);
            dbConfig.setDriver("org.apache.hive.jdbc.HiveDriver");
        }
        //2.创建连接池对象
        public static ConnectionPool connectionPool=new ConnectionPool(dbConfig);
    }
    public static ConnectionPool newInstance(){
        return Builder.connectionPool;
    }
}


public static List queryList(String sqlStr) {
        List list = null;
        Statement statement = null;
        ResultSet resultSet = null;
        ConnectionPool connectionPool = null;
        Connection connection = null;
        try {
            connectionPool = CarBonDbPoolManager.newInstance();
            connection = connectionPool.getConnection();
            statement = connection.createStatement();
            statement.execute("use gslzorder");
            resultSet = statement.executeQuery(sqlStr);
            list = new ArrayList();
            Map<String,Object> map = new HashMap<>(16);
            while (resultSet.next()){
                ResultSetMetaData metaData = resultSet.getMetaData();
                for (int i = 0; i < metaData.getColumnCount(); i++) {
                    String columnName = metaData.getColumnName(i + 1);
                    Object object = resultSet.getObject(columnName);
                    map.put(columnName,object);
                }
                list.add(map);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                if (resultSet!=null){
                    resultSet.close();
                }
                if (statement!=null){
                    statement.close();
                }
                connectionPool.releaseConnection(connection);
            } catch (SQLException throwables) {
                throw new ConnectionPoolException(ConnectionEnum.CONNECTION_CLOSE_FAIL);
            }
        }
        return list;
    }

源码地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值