与Apache DBCP的连接池 [英] Connection Pooling with Apache DBCP

查看:186
本文介绍了与Apache DBCP的连接池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Apache Commons DBCP 在Java应用程序中启用连接池(无容器 - 提供了DataSource)。在许多网站中,包括 Apache网站 - 库的使用基于以下代码段:

I want to use Apache Commons DBCP to enable connection pooling in a Java Application (no container-provided DataSource in this). In many sites of the web -including Apache site- the usage of the library is based in this snippet:

BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
ds.setUsername("scott");
ds.setPassword("tiger");
ds.setUrl(connectURI);  

然后通过getConnection()方法获取数据库连接。但在其他网站上 - 和 Apache网站也 - Datasource实例通过以下方式实现:

Then you get your DB connections through the getConnection() method. But on other sites -and Apache Site also- the Datasource instance is made through this:

ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI,null);
PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory);
ObjectPool objectPool = new GenericObjectPool(poolableConnectionFactory);
PoolingDataSource dataSource = new PoolingDataSource(objectPool);

它们之间有什么区别?我使用连接池与 BasicDataSource ,或者我需要一个 PoolingDataSource 的实例使用连接池?是 BasicDataSource 线程安全(我可以使用它作为Class属性)还是我需要同步其访问?

What's the difference between them? I'm using connection pooling with BasicDataSource, or I need an instance of PoolingDataSource to work with connection pooling? Is BasicDataSource thread-safe (can I use it as a Class attribute) or I need to synchronize its access?

推荐答案

BasicDataSource是基本需求的一切。
它在内部创建一个PoolableDataSource和一个ObjectPool。

BasicDataSource is everything for basic needs. It creates internally a PoolableDataSource and an ObjectPool.

PoolableDataSource使用提供的ObjectPool实现DataSource接口。 PoolingDataSource关心连接,ObjectPool关心保存和计数这个对象。

PoolableDataSource implements the DataSource interface using a provided ObjectPool. PoolingDataSource take cares of connections and ObjectPool take cares of holding and counting this object.

我建议使用BasicDataSource。
只有,如果你真的需要特殊的,那么你可以使用PoolingDatasource与另一个ObjectPool的实现,但它将是非常罕见和具体的。

I would recommend using BasicDataSource. Only, If you really need something special maybe then you can use PoolingDatasource with another implementation of ObjectPool, but it will be very rare and specific.

BasicDataSource是线程安全,但你应该小心使用适当的访问器,而不是直接访问受保护的字段,以确保线程安全。

BasicDataSource is thread-safe, but you should take care to use appropriate accessors rather than accessing protected fields directly to ensure thread-safety.

这篇关于与Apache DBCP的连接池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆