Java第三方数据库连接池库-DBCP-C3P0-Tomcat内置连接池

  • 连接池原理

数据库连接池的基本思想就是为数据库连接建立一个“缓冲池”。预先在缓冲池中放入一定数量的连接,当需要建立数据库连接时,只需从“缓冲池”中取出一个,使用完毕之后再放回去。我们可以通过设定连接池最大连接数来防止系统无尽的与数据库连接。

现在流行的第三方Java数据库连接池库

  • DBCP

它是Apache推出的Database Connection Pool,属于Apache Commons开源项目,官网:http://commons.apache.org/components.html。Commons的目的是提供可重用的、开源的Java代码。

使用步骤:

> 1 添加jar包  commons-dbcp-1.4.jar  commons-pool-1.5.6.jar

>2  添加属性资源文件,命名:dbcp.properties,文件放在src目录下

 

#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/database
username=
password=
#<!-- 初始化连接 -->
initialSize=10
#最大连接数量
maxActive=50
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;] 
#注意:"user""password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=utf8
#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=REPEATABLE_READ

 

> 3 编写数据源工具类

 

public class DBCPUtil {
    //得到数据源
    private static DataSource dataSource;
    static{        
        try {
            Properties pro = new Properties();
            pro.load(DBCPUtil.class.getClassLoader().getResourceAsStream("dbcp.properties"));
            //得到连接池对象,同时获取配置文件中的信息给连接池对象使用
            dataSource = BasicDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            throw new ExceptionInInitializerError("连接池初始化失败");
        }
    }
    //获取Connection对象的方法
    public static Connection getConnection() throws SQLException
    {
        return dataSource.getConnection();
    }
    //释放资源,这里的conn.close()是将连接对象放回连接池中,并不是销毁
    public static void release(Connection conn){
         if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
   }
} }

 

  • C3P0

它是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。目前使用它的开源项目有Hibernate,Spring等。

c3p0与dbcp区别:dbcp没有自动回收空闲连接的功能,c3p0有自动回收空闲连接功能。

使用步骤:

1、添加jar包  c3p0-0.9.1.2.jar,下载位置:http://www.oschina.net/p/c3p0,开源中国中有详细的下载地址。

2、编写配置文件 c3p0-config.xml,文件名固定,不能更改,【C3P0百度百科】有详细配置信息,比较全。

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
  <default-config>
<!-- 严格使用驼峰命名法,如果不是,将会出错,例如JdbcUrl就会出错。 --> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/test</property> <property name="user"></property> <property name="password"></property> <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> <property name="maxIdleTime">60</property> <!--每60秒检查所有连接池中的空闲连接。Default: 0 --> <property name="idleConnectionTestPeriod">60</property> <!--两次连接中间隔时间,单位毫秒。Default: 1000 --> <property name="acquireRetryDelay">1000</property> <!--初始化时获取10个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> <property name="initialPoolSize">0</property> <!--最大空闲时间,30秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> <property name="maxIdleTime">30</property> <!--连接池中保留的最大连接数。Default: 15 --> <property name="maxPoolSize">2</property> <property name="minPoolSize">0</property> <property name="maxStatements">200</property> <user-overrides user="test-user"> <property name="maxPoolSize">10</property> <property name="minPoolSize">1</property> <property name="maxStatements">0</property> </user-overrides> </default-config> </c3p0-config>

3、编写工具类

public class C3P0Util {
    private static ComboPooledDataSource cpds = new ComboPooledDataSource();
    private static int i=1;
    public static ComboPooledDataSource getCpds() {
        return cpds;
    }
    public static Connection getConnection(){
        Connection conn=null;
        try {
            conn=cpds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static void close(Connection ct){
        if(ct!=null){
            try {
                ct.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
  • Tomcat内置连接池

开发JavaWeb应用,必须使用一个JavaWeb服务器,JavaWeb服务器都内置数据源。

数据源只需要配置服务器即可。

 配置数据源的步骤:

1、拷贝【数据库连接的jar】tomcat的lib目录下

2、配置数据源XML文件

  a)如果把配置信息写在tomcat下的conf目录的context.xml中,那么所有应用都能使用此数据源。

  b)如果是在当前应用的META-INF中创建context.xml, 编写数据源,那么只有当前应用可以使用。

 

<Resource name="jdbc/test" 
        auth="Container" type="javax.sql.DataSource"  maxActive="100"  
        maxIdle="10" maxWait="-1"   username=""   password="" 
        driverClassName="com.mysql.jdbc.Driver" 
        url="jdbc:mysql://127.0.0.1:3306/test"/>

 

3、使用连接池

Context initContext = new InitialContext();
DataSource ds = (DataSource)initContext.lookup("java:comp/env/jdbc/test");
Connection conn = ds.getConnection();

 

 

 

 

  • JNDIjava nameing directory interface

JNDI容器就是一个Map

keyString

valueObject

path+name

对象

path+"jdbc/day16"

DataSource对象

 

 

 

 

 

 

posted @ 2016-09-23 17:01  欲戴王冠.必承其重  阅读(1030)  评论(0编辑  收藏  举报