使用DBCP配置JDBC连接池

来源:互联网 发布:java 网络编程 pdf在线 编辑:程序博客网 时间:2024/06/14 16:00

使用DBCP配置JDBC连接池

1、DBCP简介
DBCP(DataBase connection pool),数据库连接池。是 apache 上的一个 java 连接池项目,也是 tomcat 使用的连接池组件。单独使用dbcp需要2个包:commons-dbcp.jar,commons-pool.jar由于建立数据库连接是一个非常耗时耗资源的行为,所以通过连接池预先同数据库建立一些连接,放在内存中,应用程序需要建立数据库连接时直接到连接池中申请一个就行,用完后再放回去。
这里使用的版本是dbcp2。

详细介绍:http://commons.apache.org/proper/commons-dbcp/configuration.html

2、依赖jar包
commons-dbcp2-2.1.1.jar
commons-pool2-2.4.3.jar
commons-logging.jar

下载连接 http://www.apache.org/dist/commons/

3、代码示例(以Oracle为例)
1)jdbc.properties 文件

 #连接设置     #Oracle    #oracle.jdbc.driver.OracleDriver    #SqlServer    #com.microsoft.sqlserver.jdbc.SQLServerDriver    #MySql    #com.microsoft.sqlserver.jdbc.MySQLServerDriver    driverClassName=oracle.jdbc.driver.OracleDriver    url=jdbc:oracle:thin:@127.0.0.1:1521:orcl    username=admin    password=admin123    #初始化创建的连接数,当不够时再去创建    initialSize=10    #最大连接数量,连接数连不能超过该值     maxTotal=100    #最大空闲连接,当空闲连接超过该值时就挨个关闭多余的连接,但不能小于minldle    maxIdle=60    #最小空闲连接,空闲连接的最下值 -->    minIdle=10    #超时等待时间以毫秒为单位 6000毫秒/1000等于60秒,当连接超过该时间便认为其实空闲连接    maxWaitMillis=60000    #非公平锁    #useUnfairLock=true    #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒    timeBetweenEvictionRunsMillis=30000    #配置一个连接在池中最小生存的时间,单位是毫秒    minEvictableIdleTimeMillis=60000    #打开PSCache,并且指定每个连接上PSCache的大小    poolPreparedStatements=true    maxOpenPreparedStatements=100    #maxPoolPreparedStatementPerConnectionSize=20    #validationQuery=    testWhileIdle=true    testOnBorrow=false    testOnReturn=false    maxConnLifetimeMillis=300000    #连接在所指定的秒数内未使用才会被删除(秒)    removeAbandonedTimeout=60    #程序中的连接不使用后是否被连接池回收    removeAbandoned=true    removeAbandonedOnBorrow=true    removeAbandonedOnMaintenance=true    numTestsPerEvictionRun=10    logAbandoned=true    #配置监控统计拦截的filters    #filters=stat    #JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]    #注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们    connectionProperties=useUnicode=true;characterEncoding=UTF-8    #指定由连接池所创建的连接的自动提交(auto-commit)状态    defaultAutoCommit=false    #driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。    #可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE    defaultTransactionIsolation=SERIALIZABLE

2)使用连接池获取连接

 protected Connection getConnection() throws Exception {        Connection conntion = null;        BasicDataSource source = null;        try {            String filePath = super.getClass().getClassLoader().getResource("/").getPath() + "config/jdbc.properties";            filePath = URLDecoder.decode(filePath);            Properties prop = new Properties();            prop.load(new FileReader(filePath));   source = BasicDataSourceFactory.createDataSource(prop);            if(source.getConnection().isWrapperFor(OracleConnection.class)){                conntion = source.getConnection().unwrap(OracleConnection.class);            }else{                conntion = source.getConnection();            }        } catch (SQLException e) {            LOGGER.error(">> " + e.toString());            throw new RuntimeException("创建数据库连接失败!", e);        } finally {            if(source != null){                source.close();            }        }        conntion.setAutoCommit(false);        return conntion;    }

4、总结

maxIdle值与maxActive值应配置的接近。
当连接数超过maxIdle值后,刚刚使用完的连接就会立即被销毁。
若maxIdle与maxActive相差较大,在高负载的系统中会导致频繁的创建、销毁连接,影响性能。

工作快3年, 这还是第一次写博客,虽然有点简单,不过也算一个好的开始。

上面例子遇到一个问题,在Oracle数据库的环境下使用此方式配置连接池时,必须要修改Oracle数据库默认的连接数(默认150),修改到300以上,否则每次启动都会抛出ORA-12519: TNS:no appropriate service handler found 异常。

但是没有找到原因,哪位同学知道 还请告知啊。。

原创粉丝点击