Java数据库连接池比较及使用场景

我们在连接数据库的时候,由于创建数据库连接代价很大(销毁连接的代价也很大),需要消耗很多资源,因此引入数据库连接池。数据库连接池是一种池化技术,预先创建好数据库连接,保存在内存中,当需要连接时,从中取出即可,使用完后放回连接池。

下面我们介绍Java中常用的数据库连接池,主要介绍的内容有以下几点:
1. 优点及不足
2. 如何使用
3. 在哪些库或者框架中被使用。

常用的五种数据库连接池

  1. Tomcat jdbc pool
  2. C3P0
  3. HikariCP
  4. DBCP
  5. DBCP2

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.

你可能感兴趣的:(Java)