1. 程式人生 > >Java資料庫連線池比較及使用場景

Java資料庫連線池比較及使用場景

我們在連線資料庫的時候,由於建立資料庫連線代價很大(銷燬連線的代價也很大),需要消耗很多資源,因此引入資料庫連線池。資料庫連線池是一種池化技術,預先建立好資料庫連線,儲存在記憶體中,當需要連線時,從中取出即可,使用完後放回連線池。

下面我們介紹Java中常用的資料庫連線池,主要介紹的內容有以下幾點:
1. 優點及不足
2. 如何使用
3. 在哪些庫或者框架中被使用。

常用的五種資料庫連線池

Tomcat jdbc pool

優點:

  1. 高效能
  2. 併發支援好
  3. Tomcat jdbc pool implements the ability retrieve a connection asynchronously, without adding additional threads to the library itself.
  4. Tomcat jdbc pool is a Tomcat module, it depends on Tomcat JULI, a simplified logging framework used in Tomcat.

如何使用

DBCP

不足:
Commons DBCP 1.x is single threaded. In order to be thread safe Commons locks the entire pool for short periods during both object allocation and object return. Note that this does not apply to Commons DBCP 2.x.
Commons DBCP 1.x can be slow. As the number of logical CPUs grows and the number of concurrent threads attempting to borrow or return objects increases, the performance suffers. For highly concurrent systems the impact can be significant. Note that this does not apply to Commons DBCP 2.x.
Commons DBCP is over 60 classes. tomcat-jdbc-pool core is 8 classes, hence modifications for future requirement will require much less changes. This is all you need to run the connection pool itself, the rest is gravy.
Commons DBCP uses static interfaces. This means you have to use the right version for a given JRE version or you may see NoSuchMethodException exceptions.
It’s not worth rewriting over 60 classes, when a connection pool can be accomplished with a much simpler implementation.