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
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. properties will be passed explicitly, so they do not need to be included here. |
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)
|
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. |
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.
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. |
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.
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.
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
|
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.
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:
|
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. |
相关推荐
**配置DBCP数据源步骤** 1. **添加依赖**:要使用DBCP,首先需要在项目的类路径下包含两个关键的jar包,即`commons-dbcp-1.4.jar`和`commons-pool-1.6.jar`。这两个jar包提供了DBCP所需的全部功能。 2. **配置...
在SSH框架下配置DBCP数据源,首先需要将`dbcp-jar`文件添加到项目的类路径中,这个JAR包包含了DBCP所需的全部类和资源。配置过程通常包括以下几个步骤: 1. **添加依赖**:在Maven或Gradle等构建工具的配置文件中,...
例如,在Spring的XML配置文件中,你可以这样配置DBCP数据源: ```xml <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> ...
在本配置中,我们将探讨如何将Spring MVC与Apache DBCP数据源和JdbcTemplate结合使用,以实现高效、安全的数据库操作。 Apache DBCP(Database Connection Pool)是一个连接池组件,它允许应用在多个用户之间共享...
综上所述,DBCP数据源是Java应用程序中管理和复用数据库连接的有效工具,它的正确配置和使用对于提升应用性能至关重要。同时,了解并比较其他连接池方案,可以帮助选择最适合特定项目需求的解决方案。
**JDBC数据源连接池配置与使用详解** 在Java Web应用中,数据库连接的管理是至关重要的。为了提高性能和资源利用率,开发人员通常会使用数据源连接池。本篇文章将详细讲解JDBC数据源连接池的配置和使用,以帮助你更...
2. **配置参数**:在配置DBCP数据源时,需要设置一系列参数来控制连接池的行为,例如: - `driverClassName`:指定数据库驱动类名,例如"com.mysql.jdbc.Driver"对于MySQL。 - `url`:数据库连接URL,包括数据库...
例如,上述代码片段展示了如何从`jdbc.properties`文件中读取配置并构造DBCP的数据源。 总之,DBCP的数据源配置涉及到数据库连接的生命周期管理,如连接的初始化、最大并发数、空闲连接策略以及废弃连接的检测和...
首先,DBCP数据源依赖于Apache Commons DBCP库,这是一个用于创建、配置和管理数据库连接池的Java库。在Spring中集成DBCP,你需要`commons-dbcp.jar`,它提供了数据库连接池的基本功能。这个文件通常包含了数据库...
使用DBCP时,我们需要配置数据源,指定数据库连接的信息,如URL、用户名、密码等,并通过DataSource接口获取和归还连接。同时,还可以通过调整连接池的参数,如最大连接数、最小连接数、超时时间等,来优化连接池的...
在Java应用程序中,尤其是在基于Servlet和JSP的Web应用中,DBCP数据源是常用的数据库连接池解决方案之一。它允许开发者有效地管理和复用数据库连接,提高系统的性能和资源利用率。 为了使用DBCP数据源,你需要包含...
本组件"自己写的一个DAO 实现对jdbc dbcp封装 开源小组件"是作者学习研究的成果,适用于小型项目,同时也是初学者了解和实践DAO设计模式、JDBC以及Apache DBCP连接池的好材料。 1. JDBC(Java Database ...
- `commons-dbcp.jar`:这是DBCP的核心库,包含了数据库连接池的实现代码。它负责管理数据库连接的创建、分配、回收以及验证等操作。 - `commons-pool.jar`:这个库是Apache Commons的通用对象池,DBCP使用它来...
总结来说,Java连接数据库的方式多样,从基础的JDBC直接操作到使用连接池技术,如c3p0和dbcp,以及通过JNDI在应用服务器中管理数据源。根据项目需求和环境选择合适的方法,能有效提升数据库操作的效率和应用程序的...
Java Web JDBC 数据源配置 Java Web JDBC 数据源是指在 Java Web 应用程序中使用 JDBC(Java Database Connectivity)技术来连接数据库的方式。在这个配置文件中,我们可以看到的是在 Tomcat 中的 conf 文件下,...
配置Tomcat的DBCP数据源通常涉及以下几个步骤: 1. **添加依赖**:确保你的项目已经包含DBCP的依赖库。在Maven项目中,可以在pom.xml文件中添加如下依赖: ```xml <groupId>commons-dbcp <artifactId>commons-...
### Spring 数据源配置详解 #### 一、Spring与数据源简介 在Java企业级应用开发中,数据库操作是必不可少的一部分。Spring框架作为一种流行的轻量级Java应用开发框架,提供了强大的数据库访问支持,其中包括对数据...
3. **创建数据源**: 在Java代码中,通过Properties对象加载配置文件,然后创建BasicDataSource实例: ```java Properties props = new Properties(); FileInputStream fis = new FileInputStream("dbcp....