`

JDBC DBCP 数据源配置

 
阅读更多

JDBC DBCP 数据源配置 

 

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="xxxx" />
        <property name="username" value="xxx"/>
        <property name="password" value="xxx"/>

        <!--同一时该允许从连接池中获取的最大连接数,值为负数时不做限制-->
        <property name="maxActive" value="20"/>
        <!--连接池中最大的空闲连接数,如果空闲数大于此值,空闲的连接将被释放,值为负数时不做限制-->
        <property name="maxIdle" value="20"/>
        <!--连接池中最少的空闲连接数,如果空闲数少于此值,新的连接将被建立,值为0表示不限制-->
        <property name="minIdle" value="3"/>
        <!--在连接池初始化时建立的连接数-->
        <property name="initialSize" value="1"/>

        <!--等待时间:当应用需要从连接池中获取连接,而此时连接池中无可用连接,等待有连接被释放或创建新连接的时间,单位:豪秒,值为-1表示无限等待-->
        <property name="maxWait" value="60000"/>
        <!--校验连接的sql:DBCP 执行此sql校验连接的有效性,sql至少需要返回一条记录-->
        <property name="validationQuery" value="select 1 from dual"/>
        <!--校验执行超时时间:当执行校验SQL时,如果超过此时间,则认为校验失败。单位:秒,值为0或负数时,表示一直等待-->
        <property name="validationQueryTimeout" value="3"/>

        <!--在应用从池中获取连接时,是否进行连接的校验,如果校验失败,则此连接从池中移出,再试着换另一个连接返回给应用-->
        <property name="testOnBorrow" value="true"/>
        <!--应用释放连接时,连接返回到连接池,此时是否进行校验-->
        <property name="testOnReturn" value="true"/>
        <!--是否对空闲连接进行校验,如果为true,校验失败则从池中移出-->
        <property name="testWhileIdle" value="true"/>
        <!--空闲连接释放线程,执行周期,单位:毫秒-->
        <property name="timeBetweenEvictionRunsMillis" value="300000"/>
        <!--空闲连接释放线程每一次运行。检查的连接数量,默认值为3-->
        <property name="numTestsPerEvictionRun" value="3"/>
        <!--连接空闲多长时间以上,被释放,单位:毫秒-->
        <property name="minEvictableIdleTimeMillis " value="60000"/>


        <property name="removeAbandoned"><value>true</value></property>
        <property name="removeAbandonedTimeout"><value>180</value></property>
        <!--jdbc 连接属性设置-->
        <property name="connectionProperties"><value>clientEncoding=GBK</value></property>
        

        
        <!--DBCP 2版: 等待时间:当应用需要从连接池中获取连接,而此时连接池中无可用连接,等待有连接被释放或创建新连接的时间,单位:豪秒,值为-1表示无限等待-->
        <property name="maxWaitMillis" value="1000"/>
        <!--DBCP 2版:同一时该允许从连接池中获取的最大连接数,值为负数时不做限制-->
        <property name="maxTotal"><value>20</value></property>
        <!--DBCP 2版:在连接被建立时,是否进行校验,如果校验失败,则试着创建新的连接-->
        <property name="testOnCreate" value="true"/>
        <!--DBCP 2版:连接的最大生命时间,单位:毫秒-->
        <property name="maxConnLifetimeMillis" value="3600000"/>

    </bean>

 

 官方说明:Version: 2.1.1

 

BasicDataSource Configuration Parameters


Parameter Description
username

The connection username to be passed

to our JDBC driver to establish a connection.

password

The connection password to be passed to

our JDBC driver to establish a connection.

url

The connection URL to be passed to our

JDBC driver to establish a connection.

driverClassName

The fully qualified Java class name

of the JDBC driver to be used.

connectionProperties

The connection properties that will be

sent to our JDBC driver when establishing new connections. 
Format of the string must be [propertyName=property;]* 
NOTE - The "user" and "password"

properties will be passed explicitly, so they do not need to be included here.


Parameter Default Description
defaultAutoCommit driver default

The default auto-commit state of connections

created by this pool. If not set then the setAutoCommit method will not be called.

defaultReadOnly driver default

The default read-only state of connections

created by this pool. If not set then the setReadOnly

method will not be called. (Some drivers don't support read only mode, ex: Informix)

defaultTransactionIsolation driver default

The default TransactionIsolation state of connections

created by this pool. One of the following: (see javadoc)

  • NONE
  • READ_COMMITTED
  • READ_UNCOMMITTED
  • REPEATABLE_READ
  • SERIALIZABLE
defaultCatalog   The default catalog of connections created by this pool.
cacheState true

If true, the pooled connection will cache the current

readOnly and autoCommit settings when first read

or written and on all subsequent writes. This removes

the need for additional database queries for any further

calls to the getter. If the underlying connection is accessed

directly and the readOnly and/or autoCommit settings

changed the cached values will not reflect the current state.

In this case, caching should be disabled by setting this attribute to false.

defaultQueryTimeout null

If non-null, the value of this Integer property determines

the query timeout that will be used for Statements created

from connections managed by the pool. null means

that the driver default will be used.

enableAutocommitOnReturn true

If true, connections being returned to the pool will be

checked and configured with

 Connection.setAutoCommit(true) 

if the auto commit setting is false when the connection is returned.

rollbackOnReturn true

True means a connection will be rolled

back when returned to the pool

if auto commit is not enabled and the

connection is not read-only.


Parameter Default Description
initialSize 0 The initial number of connections that are created when the pool is started. 
Since: 1.2
maxTotal 8 The maximum number of active connections that can be allocated from this pool at the same time, or negative for no limit.
maxIdle 8 The maximum number of connections that can remain idle in the pool, without extra ones being released, or negative for no limit.
minIdle 0 The minimum number of connections that can remain idle in the pool, without extra ones being created, or zero to create none.
maxWaitMillis indefinitely The maximum number of milliseconds that the pool will wait (when there are no available connections) for a connection to be returned before throwing an exception, or -1 to wait indefinitely.

 NOTE: If maxIdle is set too low on heavily loaded systems it is possible you will see connections being closed and almost immediately new connections being opened. This is a result of the active threads momentarily closing connections faster than they are opening them, causing the number of idle connections to rise above maxIdle. The best value for maxIdle for heavily loaded system will vary but the default is a good starting point.


Parameter Default Description
validationQuery   The SQL query that will be used to validate connections from this pool before returning them to the caller. If specified, this query MUST be an SQL SELECT statement that returns at least one row. If not specified, connections will be validation by calling the isValid() method.
validationQueryTimeout no timeout The timeout in seconds before connection validation queries fail. If set to a positive value, this value is passed to the driver via thesetQueryTimeout method of the Statement used to execute the validation query.
testOnCreate false The indication of whether objects will be validated after creation. If the object fails to validate, the borrow attempt that triggered the object creation will fail.
testOnBorrow true The indication of whether objects will be validated before being borrowed from the pool. If the object fails to validate, it will be dropped from the pool, and we will attempt to borrow another.
testOnReturn false The indication of whether objects will be validated before being returned to the pool.
testWhileIdle false The indication of whether objects will be validated by the idle object evictor (if any). If an object fails to validate, it will be dropped from the pool.
timeBetweenEvictionRunsMillis -1 The number of milliseconds to sleep between runs of the idle object evictor thread. When non-positive, no idle object evictor thread will be run.
numTestsPerEvictionRun 3 The number of objects to examine during each run of the idle object evictor thread (if any).
minEvictableIdleTimeMillis 1000 * 60 * 30 The minimum amount of time an object may sit idle in the pool before it is eligable for eviction by the idle object evictor (if any).
softMiniEvictableIdleTimeMillis -1 The minimum amount of time a connection may sit idle in the pool before it is eligible for eviction by the idle connection evictor, with the extra condition that at least "minIdle" connections remain in the pool. When miniEvictableIdleTimeMillis is set to a positive value, miniEvictableIdleTimeMillis is examined first by the idle connection evictor - i.e. when idle connections are visited by the evictor, idle time is first compared against miniEvictableIdleTimeMillis (without considering the number of idle connections in the pool) and then against softMinEvictableIdleTimeMillis, including the minIdle constraint.
maxConnLifetimeMillis -1 The maximum lifetime in milliseconds of a connection. After this time is exceeded the connection will fail the next activation, passivation or validation test. A value of zero or less means the connection has an infinite lifetime.
logExpiredConnections true Flag to log a message indicating that a connection is being closed by the pool due to maxConnLifetimeMillis exceeded. Set this property to false to suppress expired connection logging that is turned on by default.
connectionInitSqls null A Collection of SQL statements that will be used to initialize physical connections when they are first created. These statements are executed only once - when the configured connection factory creates the connection.
lifo true True means that borrowObject returns the most recently used ("last in") connection in the pool (if there are idle connections available). False means that the pool behaves as a FIFO queue - connections are taken from the idle instance pool in the order that they are returned to the pool.

Parameter Default Description
poolPreparedStatements false Enable prepared statement pooling for this pool.
maxOpenPreparedStatements unlimited The maximum number of open statements that can be allocated from the statement pool at the same time, or negative for no limit.

 This component has also the ability to pool PreparedStatements. When enabled a statement pool will be created for each Connection and PreparedStatements created by one of the following methods will be pooled:

  • public PreparedStatement prepareStatement(String sql)
  • public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)

 NOTE - Make sure your connection has some resources left for the other statements. Pooling PreparedStatements may keep their cursors open in the database, causing a connection to run out of cursors, especially if maxOpenPreparedStatements is left at the default (unlimited) and an application opens a large number of different PreparedStatements per connection. To avoid this problem, maxOpenPreparedStatements should be set to a value less than the maximum number of cursors that can be open on a Connection.


Parameter Default Description
accessToUnderlyingConnectionAllowed false Controls if the PoolGuard allows access to the underlying connection.

When allowed you can access the underlying connection using the following construct:


    Connection conn = ds.getConnection();
    Connection dconn =((DelegatingConnection) conn).getInnermostDelegate();
    ...
    conn.close()

 Default is false, it is a potential dangerous operation and misbehaving programs can do harmful things. (closing the underlying or continue using it when the guarded connection is already closed) Be careful and only use when you need direct access to driver specific extensions.

 NOTE: Do not close the underlying connection, only the original one.


Parameter Default Description
removeAbandonedOnMaintenance
removeAbandonedOnBorrow
false Flags to remove abandoned connections if they exceed the removeAbandonedTimout.
A connection is considered abandoned and eligible for removal if it has not been used for longer than removeAbandonedTimeout.
Creating a Statement, PreparedStatement or CallableStatement or using one of these to execute a query (using one of the execute methods) resets the lastUsed property of the parent connection.
Setting one or both of these to true can recover db connections from poorly written applications which fail to close connections.
Setting removeAbandonedOnMaintenance to true removes abandoned connections on the maintenance cycle (when eviction ends). This property has no effect unless maintenance is enabled by setting timeBetweenEvicionRunsMillis to a positive value. 
If removeAbandonedOnBorrow is true, abandoned connections are removed each time a connection is borrowed from the pool, with the additional requirements that
  • getNumActive() > getMaxTotal() - 3; and
  • getNumIdle() < 2
removeAbandonedTimeout 300 Timeout in seconds before an abandoned connection can be removed.
logAbandoned false Flag to log stack traces for application code which abandoned a Statement or Connection.
Logging of abandoned Statements and Connections adds overhead for every Connection open or new Statement because a stack trace has to be generated.
abandonedUsageTracking false If true, the connection pool records a stack trace every time a method is called on a pooled connection and retains the most recent stack trace to aid debugging of abandoned connections. There is significant overhead added by setting this to true.

 If you have enabled removeAbandonedOnMaintenance or removeAbandonedOnBorrow then it is possible that a connection is reclaimed by the pool because it is considered to be abandoned. This mechanism is triggered when (getNumIdle() < 2) and (getNumActive() > getMaxTotal() - 3) and removeAbandonedOnBorrow is true; or after eviction finishes and removeAbandonedOnMaintenance is true. For example, maxTotal=20 and 18 active connections and 1 idle connection would trigger removeAbandonedOnBorrow, but only the active connections that aren't used for more then "removeAbandonedTimeout" seconds are removed (default 300 sec). Traversing a resultset doesn't count as being used. Creating a Statement, PreparedStatement or CallableStatement or using one of these to execute a query (using one of the execute methods) resets the lastUsed property of the parent connection.


Parameter Default Description
fastFailValidation false When this property is true, validation fails fast for connections that have thrown "fatal" SQLExceptions. Requests to validate disconnected connections fail immediately, with no call to the driver's isValid method or attempt to execute a validation query.
The SQL_STATE codes considered to signal fatal errors are by default the following:
  • 57P01 (ADMIN SHUTDOWN)
  • 57P02 (CRASH SHUTDOWN)
  • 57P03 (CANNOT CONNECT NOW)
  • 01002 (SQL92 disconnect error)
  • JZ0C0 (Sybase disconnect error)
  • JZ0C1 (Sybase disconnect error)
  • Any SQL_STATE code that starts with "08"
To override this default set of disconnection codes, set the disconnectionSqlCodes property.
disconnectionSqlCodes null Comma-delimited list of SQL_STATE codes considered to signal fatal disconnection errors. Setting this property has no effect unlessfastFailValidation is set to true.
分享到:
评论

相关推荐

    Spring_c3p0与dbcp数据源_的配置

    Spring_c3p0与dbcp数据源_的配置.doc 很不错的哦!拿出来和大家一起学习!

    Spring3中配置DBCP,C3P0,Proxool,Bonecp数据源

    在Spring3中配置数据源,包括DBCP,C3P0,Proxool,Bonecp主要的数据源,里面包含这些数据源的jar文件和依赖文件及配置文件。。 如Bonecp目前听说是最快的数据源,速度是传统的c3p0的25倍, bonecp.properties文件: ...

    jdbc的jar包.zip

    DBCP 是 Apache 软件基金组织下的开源连接池实现,要使用DBCP数据源,需要应用程序应在系统中增加如下两个 jar 1. Commons-dbcp.jar:连接池的实现 ...

    JAVAWEB-16:JDBC编程进阶(自定义数据源+开源数据源:DBCP、C3P0)

    JAVAWEB-16:JDBC编程进阶(自定义数据源+开源数据源:DBCP、C3P0)

    java web 开发jdbc数据源jar包

    java web 开发用到的jdbc数据源jar包commons-dbcp-1.4.jar 和commons-pool-1.5.3.jar

    spring Ioc容器配置

    IOC容器数据源配置 &lt;!-- 配置数据源 --&gt; &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt; &lt;value&gt;org.gjt.mm.mysql.Driver &lt;value&gt;jdbc:mysql:/...

    Spring Data JDBC与JDBC的区别

     DataSource:数据源  DriverManager:驱动管理  Driver:JDBC驱动  Connection:数据库连接  Statement:语句,执行SQL  PrepareStatement:预编译语句,性能更好  CallableStatement:调用存储过程  ...

    tomcat 配置数据源

    &lt;value&gt;org.apache.commons.dbcp.BasicDataSourceFactory &lt;name&gt;maxActive &lt;value&gt;100 &lt;name&gt;maxIdle &lt;value&gt;30 &lt;name&gt;maxWait &lt;value&gt;5000 &lt;name&gt;username ...

    基于 SpringBoot 多数据源 动态数据源 主从分离 快速启动器 支持分布式事务

    基于 SpringBoot 多数据源 动态数据源 主从分离 快速启动器 支持分布式事务。一个基于springboot的快速集成多数据源的启动器。支持 数据源分组 ,适用于多种场景 纯粹多库 读写分离 一主多从 混合模式。支持数据库...

    基于框架的Web开发-使用springJDBC入门.doc

    (4) dbcp数据源:commons-dbcp、commons-pool (5) junit: junit、hamcrest (6) mysql 驱动 2 数据库准备 本章文件夹下有sampledb.sql文件,将其导入mysql中,会创建一个数据库sampledb,包含两张数据表。导入方法如...

    ssh框架在application.xml中配置数据源所需jar

    class="org.apache.commons.dbcp.BasicDataSource"&gt; value="${database.driver}"&gt; ${database.url}"&gt; ${database.username}"&gt; ${database.password}"&gt; class="org.springframework.orm....

    使用Spring JDBC 案例

    有spring jdbctemplate 增删改查 配置spring自带的、c3p0、dbcp、druid 4种连接池 以及读取jdbc.properties数据源 自己写的一个行映射器工具类

    JDBC常用连接池 c3p0 BDCP Druid

    DBCP (Database Connection Pool)是一个依赖Jakarta commons-pool对象池机制的数据库连接池,Tomcat的数据源使用的就是DBCP。目前 DBCP 有两个版本分别是 1.3 和 1.4。1.3 版本对应的是 JDK 1.4-1.5 和 JDBC 3,而...

    tomcat JDNI配置

    一个简单的tomcat6.0+mysql5.5整合spring3.0和hibernate3.3的一个简单的实例,其中的datasource是tomcat JNDI配置的 &lt;Resource name="jdbc/testDB" type="javax.sql.DataSource" driverClassName=...

    JDBC专题(七)-数据库连接池 DataSource Pool.docx

    4.1.DBCP数据源 4.2.C3P0连接池 4.3.Druid连接池 4.3.1.druid连接池的使用 1.应用程序直接获取数据库连接的缺点 用户每次请求都需要向数据库获得链接,而数据库创建连接通常需要消耗相对较大的资源,...

    使用JDBC连接,DBCP连接池实现的基础记账功能小程序。增删改查的练手实践项目。.zip

    爬虫通常由搜索引擎、数据挖掘工具、监测系统等应用于网络数据抓取的场景。 爬虫的工作流程包括以下几个关键步骤: URL收集: 爬虫从一个或多个初始URL开始,递归或迭代地发现新的URL,构建一个URL队列。这些URL...

    Druid(JDBC组件) v1.2.18

    Spring Boot 2.0 以上默认使用 Hikari 数据源,可以说 Hikari 与 Driud 都是当前 Java Web 上最优秀的数据源,我们来重点介绍 Spring Boot 如何集成 Druid 数据源,如何实现数据库监控。 Druid的主要特点 1.列式...

    tomcat_连接池数据库密码加密解密方法

    详细讲解tomcat 连接池数据库解密加密方法以及过程。

    dynamic-datasource-spring-boot-starter-v3.5.1.zip

    Dynamic-Datasource (opens new window)- 基于 SpringBoot 的多数据源组件,功能强悍,支持 Seata 分布式事务。 支持 数据源分组 ,适用于多种场景 纯粹多库 读写分离 一主多从 混合模式。 支持数据库敏感配置信息 ...

Global site tag (gtag.js) - Google Analytics