连接池创建多连接方法的封装

来源:互联网 发布:淘宝打折工具在哪里 编辑:程序博客网 时间:2024/06/06 13:04

连接池创建多连接方法的封装


一.首先介绍一些需要用到的难理解的一切知识点:

ArrayBlockingQueue<E>: 是一个由数组支持的有界阻塞队列。此队列按 FIFO(先进先出)原则对元素进行排序。队列的头部 是在队列中存在时间最长的元素。队列的尾部 是在队列中存在时间最短的元素。新元素插入到队列的尾部,队列获取操作则是从队列头部开始获得元素。

已实现的接口:Serializable, Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E>

官方api给出的构造方法:

  • ArrayBlockingQueue(int capacity);

Creates an ArrayBlockingQueue with the given (fixed) capacity and default access policy.
//创建一个带有给定的(固定)容量和默认访问策略的 ArrayBlockingQueue

  • ArrayBlockingQueue(int capacity, boolean fair);

Creates an ArrayBlockingQueue with the given (fixed) capacity and the specified access policy.
//创建一个具有给定的(固定)容量和指定访问策略的 ArrayBlockingQueue

  • ArrayBlockingQueue(int capacity, boolean fair, Collection<? extends
    E> c);

Creates an ArrayBlockingQueue with the given (fixed) capacity, the specified access policy and initially containing the elements of the given collection, added in traversal order of the collection’s iterator.
//创建一个具有给定的(固定)容量和指定访问策略的 ArrayBlockingQueue,它最初包含给定 collection 的元素,并以 collection 迭代器的遍历顺序添加元素

我们所要使用到的方法主要有:put(E e) void    将指定的元素插入此队列的尾部,如果该队列已满,则等待可用的空间。take() E    获取并移除此队列的头部,在元素变得可用之前一直等待(如果有必要)。pull() E    获取并移除此队列的头,如果此队列为空,则返回 null。poll(long timeout, TimeUnit unit) E  获取并移除此队列的头部,在指定的等待时间前等待可用的元素(如果有必要)

二.接下来我们开始封装

当我们需要用创建多个连接切使用连接方式为连接池时,我们可以抽象出一种思想。建立一个公共的创建连接的类,当我们创建连接时我们只需要调用该方法的getConnection()方法,即可获得该连接池对应的对象。以用来提交代码的重用性! 废话不多说上代码吧~直接明了

public class DBConnection {    private Logger logger = LoggerFactory.getLogger(DBConnection.class);    private String username;//对应连接的账户名    private String password;//对应连接的密码    private String url;//对应uri    private String driver;//所需加载的驱动    private int type;    private Connection connection;//连接对象    private PreparedStatement ps = null;    private ResultSet rs = null;//要返回的结果集    DBConnection(String username, String password, String url, String driver, int type) {//通过构造方法取对应信息        this.url = url;        this.username = username;        this.driver = driver;        this.password = password;        this.type = type;        this.createConnection();    }    private void createConnection() {//创建连接        logger.info("DBConnection createConnection url [{}]", url);        try {            Class.forName(this.driver);//反射机制读取driver            this.connection = DriverManager.getConnection(url, username, password);        } catch (ClassNotFoundException | SQLException e) {            logger.error("DBConnection.createConnection", e);        }    }    PreparedStatement pareparedStatement(String sql) throws SQLException {        return connection.prepareStatement(sql);//因此处模拟mysql和hive连接池创建连接所以需预处理对应sql    }    public ResultSet getResultSet(String sql) throws SQLException {//重新封装        ps = pareparedStatement(sql);        rs = ps.executeQuery();        return rs;    }    int excuteUpdate(String sql) throws SQLException {        return pareparedStatement(sql).executeUpdate();    }    boolean excute(String sql) throws SQLException {        return pareparedStatement(sql).execute();    }    public void close() {//判空并关闭        try {            if (rs != null)                rs.close();            if (ps != null)                ps.close();        } catch (SQLException e) {            e.printStackTrace();        }    }    public Connection getConnection() {//我们只需要调用此方法即可获得相应连接        return connection;    }    public void setConnection(Connection connection) {        this.connection = connection;    }    public int getType() {        return type;    }    public void setType(int type) {        this.type = type;    }}

以上就是封装好的DBConnection连接池类,有人会问我们为什么要采用连接池创建连接而不是普通形式的连接呢,这里引用一篇博客来说明一下,着重于第二点和第三点http://www.cnblogs.com/aspirant/p/6747238.html 。

那么我们要怎么去利用我们封装好的这个类呢。废话还是不多说直接上代码

public class DBConnectionPool {    private static Logger logger = LoggerFactory.getLogger(DBConnectionPool.class);    private static ArrayBlockingQueue<DBConnection> mysql_pool;    private static ArrayBlockingQueue<DBConnection> hive_pool;    /**     * 规定了连接池中的连接数     */    private static final int totalActive = totalActive;    private static final int MYSQL=0;     private static final int HIVE =1;    private static String mysql_url = mysql_url;    private static String hive_url = hive_url;    private static String mysql_username = mysql_username;    private static String hive_username = hive_username;    private static String mysql_password = mysql_password;    private static String hive_password = hive_password;    private static String mysql_driver = mysql_driver;    private static String hive_driver = hive_driver;    /**     * 初始化连接池     */    public void init() {        mysql_pool = new ArrayBlockingQueue<>(totalActive);//这里也就是开篇介绍的类的作用了        hive_pool = new ArrayBlockingQueue<>(totalActive);        int i = 0;        while (i < totalActive) {            try {                mysql_pool.put(getMysqlConnection());                hive_pool.put(getHiveConnection());                i++;            } catch (InterruptedException e) {                logger.error("DBConnection.init init Failed ", e);            }        }        logger.info("DBConnectionPool intialize total [{}]", i);    }    /**     * 根据type参数生成单个连接池     *     * @param type 0为mysql ,1 为hive     */    public void init(int type) {        if (type == MYSQL)            mysql_pool = new ArrayBlockingQueue<>(totalActive);        else if (type == HIVE)            hive_pool = new ArrayBlockingQueue<>(totalActive);        int i = 0;        try {            while (i < totalActive) {                if (type == MYSQL) {                    mysql_pool.put(getConnection(MYSQL));                }                if (type == CommonConst.HIVE) {                    hive_pool.put(getConnection(HIVE));                }                i++;            }        } catch (InterruptedException e) {            logger.error("DBConnectionPool.init type[{}], error", type == MYSQL ? "MYSQL" : "HIVE", e);        }    }    private DBConnection getMysqlConnection() {        return new DBConnection(mysql_username, mysql_password, mysql_url, mysql_driver, MYSQL);//创建mysql连接    }    private DBConnection getHiveConnection() {        return new DBConnection(hive_username, hive_password, hive_url, hive_driver, HIVE);    }    /**     * 将连接放回     *     * @param connection     */    public static void returnConnection(DBConnection connection) {        try {            connection.close();            if (connection.getType() == MYSQL)                 mysql_pool.put(connection);            if (connection.getType() == HIVE)                 hive_pool.put(connection);        } catch (InterruptedException e) {            logger.error("DBConnection.getConnection error ", e);        }    }    /**     * 返回连接     */    public static void returnConnection(DBConnection connection, ResultSet rs) {        try {            returnConnection(connection);            if (rs != null) rs.close();        } catch (SQLException e) {            e.printStackTrace();        }    }    static void returnConnection(DBConnection connection, PreparedStatement ps, ResultSet rs) {        returnConnection(connection, rs);        if (ps != null)            try {                ps.close();            } catch (SQLException e) {                e.printStackTrace();            }    }    /**     * 根据类型活的对应连接     *     * @param type 0为mysql连接, 1为 Hive连接, 根据常量表中获取常量插入     * @return     */    public static DBConnection getConnection(int type) {        DBConnection connection = null;        try {            if (type == MYSQL)                connection = mysql_pool.take();            else if (type == HIVE)                connection = hive_pool.take();        } catch (InterruptedException e) {            logger.error("DBConnection.getConnection error type", type, e);        }        return connection;    }    public static void destroyAll() {//关闭所有        try {            while (true) {                DBConnection connection_hive = hive_pool.poll();                DBConnection connection_mysql = mysql_pool.poll();                if (connection_hive == null && connection_mysql == null)                    break;                if (connection_hive != null)                    connection_hive.getConnection().close();                if (connection_mysql != null)                    connection_mysql.getConnection().close();            }        } catch (SQLException e) {            logger.error("DBConnector.destroyAll error", e);        }    }}

以上就是对连接池创连接的方法了,鄙人菜鸟一枚 如有破绽漏洞或者哪里不符规矩还请指出。欢迎大家在评论区留下你宝贵的意见。谢谢您阅读!如有雷同纯属巧合!

原创粉丝点击