数据源(数据库连接池)

来源:互联网 发布:消防大数据内容 编辑:程序博客网 时间:2024/04/30 10:56

数据源(数据库连接池)


介绍

数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个;这项技术能明显提高对数据库操作的性能。简单理解DataSource是一个管理数据库连接Connection对象的容器。可以这么看DataSource类似List

java数据源介绍

使用数据库连接池的优点:

1、资源重用2、更快的系统响应速度3、新的资源分配手段4、统一的连接管理,避免数据库连接的泄漏

JDBC的数据库连接池使用javax.sql.DataSouce接口,任何想要使用JDBC数据源方法的第三方组件都需要实现该接口。

典型的两种开源数据源

1、DBCP的实现数据源为BasicDataSouce,可以使用BasicDataSourceFactory的createDataSource(Properties properties)方法来创建数据源。使用properties配置文件。

2、C3P0的实现数据源为ComboPooledDataSource。c3p0数据源是使用c3p0-config.xml配置文件的,不要修改它的默认名字。否则加载不了。

备注:Spring推荐使用DBCP数据源、Hibernate推荐使用C3P0数据源。DBCP稳定性更强,C3P0数据源并发性高的时候更有优势。

C3P0数据源的使用

基于java代码方式

//初始化对象ComboPooledDataSource dataSource = new ComboPooledDataSource();dataSource.setDriverClass("com.mysql.jdbc.Driver");dataSource.setJdbcUrl("jdbc:mysql://localhost/test");dataSource.setUser("root");dataSource.setPassword("admin");dataSource.setInitialPoolSize(5);...设置参数

基于配置文件方式

c3p0-config.xml配置文件如下:

<?xml version="1.0" encoding="UTF-8"?><c3p0-config>    <named-config name="c3p0">        <!-- 指定连接数据源的基本属性 -->        <property name="user">root</property>        <property name="password">admin</property>        <property name="driverClass">com.mysql.jdbc.Driver</property>        <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>        <!-- 若数据库中连接数不足时, 一次向数据库服务器申请多少个连接 -->        <property name="acquireIncrement">5</property>        <!-- 初始化数据库连接池时连接的数量 -->        <property name="initialPoolSize">5</property>        <!-- 数据库连接池中的最小的数据库连接数 -->        <property name="minPoolSize">5</property>        <!-- 数据库连接池中的最大的数据库连接数 -->        <property name="maxPoolSize">10</property>        <!-- C3P0 数据库连接池可以维护的 Statement 的个数 -->        <property name="maxStatements">20</property>        <!-- 每个连接同时可以使用的 Statement 对象的个数 -->        <property name="maxStatementsPerConnection">5</property>    </named-config></c3p0-config>

初始化数据源如下:

// 使用new ComboPooledDataSource(String// configName)初始化获得数据源对象,configName为c3p0-config配置文件的named-config标签的name属性值ComboPooledDataSource dataSource = new ComboPooledDataSource("c3p0");Connection connection = dataSource.getConnection();备注:数据源只需要初始化一次就行了,所以应该将其初始化放入static代码块中

备注:

数据库连接池获得的Connection对象的close()方法并不是真正的关闭资源,而是把数据库连接资源归还给数据库连接池。因为通过数据源获得的连接对象其实是一个代理对象并不是真正的Connection对象

参考

http://www.mchange.com/projects/c3p0/#quickstart
http://commons.apache.org/proper/commons-dbcp/index.html
http://www.cnblogs.com/xdp-gacl/p/4002804.html
http://blog.sina.com.cn/s/blog_6f688450010148d2.html

0 0
原创粉丝点击