java通過dbcp實現(xiàn)一個數(shù)據(jù)庫連接池

前言

對于spring項目,如果需要用到多數(shù)據(jù)源,可以直接在spirng配置多個數(shù)據(jù)源,但是這種方法比較麻煩,特別是項目整合了mybatis的情況,如果我們只需要很簡單地訪問另外一個數(shù)據(jù)庫,我們完全可以通過dbcp實現(xiàn)一個簡單的連接池即可。

實現(xiàn)

一開始,我們可以用純粹的jdbc來連接數(shù)據(jù)庫,但是這樣,我們每次訪問數(shù)據(jù)庫,都需要開啟連接和關閉連接,非常浪費資源,因此,我們可以實現(xiàn)一個簡單的連接池,用于減少這部分資源的開銷。并且,我們不需要自己實現(xiàn)連接池的功能,各大廠商都已經為我們提供了連接池的實現(xiàn),例如C3P0、DBCP連接池等,我們只需在這基礎上二次開發(fā)即可,這里,我們選用DBCP來實現(xiàn)我們的連接池功能。

  • pom.xml配置
<dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
</dependency>
  • config.properties配置連接屬性
#other database
other.jdbc.driver=com.mysql.jdbc.Driver
other.jdbc.url=jdbc:mysql://localhost:3306/spring_test?useUnicode=true&characterEncoding=utf-8
other.jdbc.user=root
other.jdbc.password=root
other.initSize=1
other.maxAtive=8
other.maxWait=60000
other.maxIdle=6
other.minIdle=2
  • 連接池工具類

這里使用了ThreadLocal類,主要是通過該類實現(xiàn)同步效果,防止多線程下該連接池失效。

public class DbUtil {

    private static final Logger log = LoggerFactory.getLogger(DbUtil.class);

    /**
     *  數(shù)據(jù)庫連接池
     */
    private static BasicDataSource dbcp;

    /**
     *  為不同線程管理連接
     */
    private static ThreadLocal<Connection> threadLocal;

    static {
        try {
            dbcp = new BasicDataSource();
            dbcp.setDriverClassName(PropertyUtil.getProperty("config", "other.jdbc.driver"));
            dbcp.setUrl(PropertyUtil.getProperty("config", "other.jdbc.url"));
            dbcp.setUsername(PropertyUtil.getProperty("config", "other.jdbc.user"));
            dbcp.setPassword(PropertyUtil.getProperty("config", "other.jdbc.password"));
            // 初始化
            dbcp.setInitialSize(Integer.parseInt(PropertyUtil.getProperty("config", "other.initSize")));
            // 最大連接數(shù)
            dbcp.setMaxActive(Integer.parseInt(PropertyUtil.getProperty("config", "other.maxAtive")));
            // 最大等待時間
            dbcp.setMaxWait(Long.parseLong(PropertyUtil.getProperty("config", "other.maxWait")));
            // 最大空閑數(shù)
            dbcp.setMaxIdle(Integer.parseInt(PropertyUtil.getProperty("config", "other.maxIdle")));
            // 最小空閑數(shù)
            dbcp.setMinIdle(Integer.parseInt(PropertyUtil.getProperty("config", "other.minIdle")));

            threadLocal = new ThreadLocal<>();

        } catch (Exception e) {
            log.error("DbUtil exception",e);
        }
    }

    /**
     * 獲取一個連接
     * @return
     */
    public static Connection getConnection() {
        try {
            Connection connection = dbcp.getConnection();
            connection.setAutoCommit(false);
            threadLocal.set(connection);
            return connection;
        } catch (Exception e) {
            log.error("getConnection exception",e);
            return null;
        }
    }

    /**
     * 歸還一個連接
     */
    public static void closeConnection() {
        try {
            Connection connection = threadLocal.get();
            if(connection != null) {
                // 實際上沒有關閉連接,只是放在池子里
                connection.close();
                threadLocal.remove();
            }
        } catch (Exception e) {
            log.error("closeConnection exception",e);
        }

    }
}
  • 利用junit來進行測試
@Test
public void testDbUtil(){
    String sql = "select * from study_login";
    Connection connection = DbUtil.getConnection();
    try{
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()){
            System.out.println(resultSet.getInt(1));
            System.out.println(resultSet.getString(2));
            System.out.println(resultSet.getString(3));
        }
    }catch (Exception e){
        logger.error("testDbUtil exception", e);
    }


}

源碼

詳細代碼請參考github的DbUtil.java

https://github.com/wumingzhizhu/springTest

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 前言 數(shù)據(jù)庫連接池在Java數(shù)據(jù)庫相關中間件產品群中,應該算是底層最基礎的一類產品,作為企業(yè)應用開發(fā)必不可少的組件...
    許da廣閱讀 7,462評論 2 27
  • JDBC Java 數(shù)據(jù)庫連接(Java Database Connectivity,簡稱JDBC)是 Java ...
    狗子渣渣閱讀 2,062評論 0 10
  • 最原始的數(shù)據(jù)庫連接就是我們打開一個連接,使用過后再關閉該鏈接來釋放資源。頻繁的新建打開再關閉連接對jvm和數(shù)據(jù)庫都...
    野柳閱讀 6,593評論 1 11
  • Java 為數(shù)據(jù)庫連接池提供了公共的接口:javax.sql.DataSource,各個廠商需要讓自 己的連接池實...
    勝浩_ae28閱讀 1,433評論 0 2
  • 在ios開發(fā)中,使用圖片的方式有兩種一種方式可以將圖片散落在工程中,一種方式可以用bundle統(tǒng)一管理。 文件形式...
    mymdeep閱讀 4,256評論 2 2

友情鏈接更多精彩內容