设为首页 收藏本站
查看: 832|回复: 0

[经验分享] (翻译)Tomcat JDBC 连接池

[复制链接]

尚未签到

发表于 2017-1-23 09:01:37 | 显示全部楼层 |阅读模式
介绍
org.apache.tomcat.jdbc.pool包的JDBC连接池被用来替代commons-dbcp连接池。

为什么我们需要一个新的连接池?

有这样一些原因:

1.      commons-dbcp是单线程的,即使是查询验证过程也以线程锁锁定整个池。
2.      commons-dbcp性能低下——在cpu核心数量不断成长的今天,即使Java6对同步关键字提供巨大优化效果,commons-dbcp仍然不支持高并发。
3.      commons-dbcp复杂度高,超过60个类,tomcat-jdbc-pool只有8个核心类,可以最小修改量应对对未来需求。你需要的仅仅是一个连接池,其他的都不重要。
4.      commons-dbcp使用静态接口。意味着你不能在JDK1.6下编译它,否则即使驱动程序支持的方法,dbcp不支持的方法,在运行时也将出现NoSuchMethodException异常。
5.      commons-dbcp呆滞。更新、释放和对新特性的支持相当缓慢。
6.      如果可以简单得多的方式实现连接池,我们就不需要重写60多个类。
7.      Tomcat JDBC连接池支持公平列队选项,这在commons-dbcp上是不支持的,但性能仍然比commons-dbcp快。
8.      Tomcat JDBC连接池可以在不开启新线程的情况下异步地回收连接。
9.      Tomcat JDBC连接池吃一个Tomcat模块,依赖于TomcatJULI——一个Tomcat使用的精简的日志框架。
10.  收回使用javax.sql.PooledConnection接口的相关连接。
11.  饥饿测试。如果一个池是空的,并且有线程正在等待一个连接,当一个连接被退还,这个池将唤醒当前等待的线程。多数连接池会被饿死。
相比其他连接池实现增加的特性:

1.      支持多线程环节和多核心/cpu系统。
2.      动态实现接口,可支持特定runtime的java.sql和javax.sql接口(需JDBC驱动支持),即使在低版本的JDK编译。
3.      验证间隔——没有在每次使用连接时进行验证,而仅仅在取用和归还连接时,我们只需要配置最高验证频率。
4.      单次查询——当数据库创建连接之后,可以执行一个可配置的查询。当你需要整个连接期间只需要查询一次的话,这个功能非常有用。
5.      可以配置自定义拦截器。允许你自定义拦截器来增加新的功能。可以利用拦截器收集查询状态,缓存会话状态,连接失败重连,重试查询,缓存查询结果等等。动态的拦截器使你有无穷的创意,不必被JDK提供的java.sql/javax.sql接口捆绑。
6.      高性能——稍候我们将展示不同的性能表现。
7.      简单扩展,因为有非常简单的实现,代码行数和源文件数量都非常少,对比c3p0拥有200多个源文件(上次我们检查的结果),Tomcat JDBC连接池只有8个核心文件,连接池本身更只有一半大小。如果出现bug,他们非常容易跟踪和修复。降低复杂度更能集中精力。
8.      异步连接回收——你可以执行一个查询,并使用Future<Connection>异步取得。
9.      更好的闲置连接处理。相比直接关闭闲置连接,它能回收连接并使用更智能的算法修整闲置连接大小。
10.  你可以决定什么时候考虑丢弃一个连接,当连接池满,或直接设置一个超时。
11.  丢弃的连接计数器将在statement/query完成之后。允许一个正在被使用的连接存在更长时间而不超时。这个功能由ResetAbandonedTimer实现。
12.  指定在连接创建后一个时间点关闭它。基于连接回收次数控制。
13.  连接被丢弃后发送JMX通知和日志条目。这和removeAbandonedTimeout非常相似,但不做任何动作,只是报告一条消息。这个实现使用suspectTimeout属性。
14.  可以通过java.sql.Driver, javax.sql.DataSourcejavax.sql.XADataSource取得连接,这个实现使用dataSource和dataSourceJNDI属性。
15.  支持XA连接。
使用方法
         为了熟悉commons-dbcp的用户,Tomcat连接池的使用方法被设计得尽可能简单,过度非常简单。从其他连接池迁移也很容易。

附加特性
         Tomcat连接池在其他连接池之外还提供一些附加特性:

initSQL——在连接建立之后执行一次SQL
验证间隔——避免高频率的验证
Jdbc拦截器——灵活、可插拔的拦截器,可自定义连接池、查询和结果集。更多描述在高级部分
公平列队——设置fair标记为true来实现公平或异步连接回收
集成Apache Tomcat 容器
         遵守TheTomcat JDBC documentation描述,Tomcat连接池被配置为一个资源,。唯一的不同是你必须指定factory属性,并且这是value为org.apache.tomcat.jdbc.pool.DataSourceFactory

独立运行
         连接池只有一个依赖——tomcat-juli.jar。使用org.apache.tomcat.jdbc.pool.DataSource类实例Bean在独立项目中配置连接池。你可以用后面描述的属性,像使用Bean一样将连接池配置为JNDI资源。
JMX
         连接池对象公开一个可以被注册的Mbean。jmxEnabled属性必须设为true,连接池才会建立MBean。连接池不负责注册这个Mbean,只负责建立。**杜天微注:后面与我们无关了,先不翻译了。
属性
为了简化切换commons-dbcp和Tomcat JDBC池,多数属性和commons-dbcp相同,并有相同的意义。
JNDI Factory和Type
属性
描述
Factory
Factory是必需的,并且值必须为org.apache.tomcat.jdbc.pool.DataSourceFactory

Type
类型应该永远为javax.sql.DataSourcejavax.sql.XADataSource

根据类型不同,org.apache.tomcat.jdbc.pool.DataSourceorg.apache.tomcat.jdbc.pool.XADataSource对象将被建立。

 
  
普通属性
         这些属性是commons-dbcp和tomcat-jdbc-pool共享的,有些属性的默认值不同。**杜天微注:这个常用不翻译了
 

Attribute

Description

defaultAutoCommit

(boolean) The default auto-commit state of connections created by thispool. If not set, default is JDBC driver default (If not set then the setAutoCommit method will not be called.)

defaultReadOnly

(boolean) The default read-only state of connections created by thispool. If not set then the setReadOnly methodwill not be called. (Some drivers don't support read only mode, ex:Informix)

defaultTransactionIsolation

(String) The default TransactionIsolation state of connections createdby this pool. One of the following: (see javadoc )


  • NONE
  • READ_COMMITTED
  • READ_UNCOMMITTED
  • REPEATABLE_READ
  • SERIALIZABLE
If not set, the method will not be called and itdefaults to the JDBC driver.

defaultCatalog

(String) The default catalog of connections created by this pool.

driverClassName

(String) The fully qualified Java class name of the JDBC driver to beused. The driver has to be accessible from the same classloader astomcat-jdbc.jar

username

(String) The connection username to be passed to our JDBC driver toestablish a connection. Note, at this point, DataSource.getConnection(username,password) is not using the credentials passed into themethod.

password

(String) The connection password to be passed to our JDBC driver toestablish a connection. Note, at this point, DataSource.getConnection(username,password) is not using the credentials passed into themethod.

maxActive

(int) The maximum number of active connections that can be allocatedfrom this pool at the same time. The default value is 100

maxIdle

(int) The maximum number of connections that should be kept in thepool at all times. Default value is maxActive:100 Idleconnections are checked periodically (if enabled) and connections that beenidle for longer than minEvictableIdleTimeMillis will be released. (also see testWhileIdle)

minIdle

(int) The minimum number of established connections that should bekept in the pool at all times. The connection pool can shrink below thisnumber if validation queries fail. Default value is derived from initialSize:10 (also see testWhileIdle)

initialSize

(int)The initial number of connections that are created when the poolis started. Default value is 10

maxWait

(int) The maximum number of milliseconds that the pool will wait (whenthere are no available connections) for a connection to be returned beforethrowing an exception. Default value is 30000 (30 seconds)

testOnBorrow

(boolean) The indication of whether objects will be validated beforebeing borrowed from the pool. If the object fails to validate, it will bedropped from the pool, and we will attempt to borrow another. NOTE - for atrue value to have any effect, the validationQuery parameter must be set to a non-null string. Inorder to have a more efficient validation, see validationInterval. Default value is false

testOnReturn

(boolean) The indication of whether objects will be validated beforebeing returned to the pool. NOTE - for a true value to have any effect, thevalidationQuery parameter must be set to a non-null string. Thedefault value is false.

testWhileIdle

(boolean) The indication of whether objects will be validated by theidle object evictor (if any). If an object fails to validate, it will bedropped from the pool. NOTE - for a true value to have any effect, the validationQuery parameter must be set to a non-null string. Thedefault value is false and thisproperty has to be set in order for the pool cleaner/test thread is to run(also see timeBetweenEvictionRunsMillis)

validationQuery

(String) The SQL query that will be used to validate connections fromthis pool before returning them to the caller. If specified, this querydoes not have to return any data, it just can't throw a SQLException. The default value is null. Example values are SELECT 1(mysql),select 1 fromdual(oracle), SELECT 1(MS Sql Server)

validatorClassName

(String) The name of a class which implements the org.apache.tomcat.jdbc.pool.Validator interface and provides a no-arg constructor (maybe implicit). If specified, the class will be used to create a Validatorinstance which is then used instead of any validation query to validateconnections. The default value is null. An examplevalue is com.mycompany.project.SimpleValidator.

timeBetweenEvictionRunsMillis

(int) The number of milliseconds to sleep between runs of the idleconnection validation/cleaner thread. This value should not be set under 1second. It dictates how often we check for idle, abandoned connections, andhow often we validate idle connections. The default value is 5000 (5 seconds).

numTestsPerEvictionRun

(int) Property not used in tomcat-jdbc-pool.

minEvictableIdleTimeMillis

(int) The minimum amount of time an object may sit idle in the poolbefore it is eligible for eviction. The default value is 60000 (60 seconds).

accessToUnderlyingConnectionAllowed

(boolean) Property not used. Access can be achieved by calling unwrap on the pooled connection. see javax.sql.DataSource interface, or call getConnection through reflection or or cast the object as javax.sql.PooledConnection

removeAbandoned

(boolean) Flag to remove abandoned connections if they exceed the removeAbandonedTimout. If set to true a connection is consideredabandoned and eligible for removal if it has been in use longer than the removeAbandonedTimeout Setting this to true can recover db connections from applications that fail to close aconnection. See also logAbandoned Thedefault value is false.

removeAbandonedTimeout

(int) Timeout in seconds before an abandoned(in use) connection can beremoved. The default value is 60 (60 seconds).The value should be set to the longest running query your applicationsmight have.

logAbandoned

(boolean) Flag to log stack traces for application code whichabandoned a Connection. Logging of abandoned Connections adds overhead forevery Connection borrow because a stack trace has to be generated. Thedefault value is false.

connectionProperties

(String) The connection properties that will be sent to our JDBCdriver 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 notneed to be included here. The default value is null.

poolPreparedStatements

(boolean) Property not used.

maxOpenPreparedStatements

(int) Property not used.

 

Tomcat连接池增加的属性
 

Attribute

Description

initSQL

(String)当连接第一次建立时执行的SQL,默认值为null。

A custom query to be run when a connection is firstcreated. The default value is null.

jdbcInterceptors

(String) A semicolon separated list of classnamesextending org.apache.tomcat.jdbc.pool.JdbcInterceptor class. These interceptors will be inserted as aninterceptor into the chain of operations on a java.sql.Connection object. The default value is null.
Predefined interceptors:
org.apache.tomcat.jdbc.pool.interceptor.ConnectionState - keeps track of auto commit, read only, catalog andtransaction isolation level.
org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer - keeps track of opened statements, and closes themwhen the connection is returned to the pool.
More predefined interceptors are described in detail in the JDBCInterceptors section.

validationInterval

(long) 避免过度验证,保证验证不超过这个频率——以毫秒为单位。如果一个连接应该被验证,但上次验证未达到指定间隔,将不再次验证。默认值是30000(30秒)。

avoid excess validation, only run validation at mostat this frequency - time in milliseconds. If a connection is due forvalidation, but has been validated previously within this interval, it willnot be validated again. The default value is 30000 (30seconds).

jmxEnabled

(boolean) Register the pool with JMX or not. Thedefault value is true.

fairQueue

(boolean) 如果被设为true,getConnection方法将被以先进先出的方式对待。此属性使用 org.apache.tomcat.jdbc.pool.FairBlockingQueue实现闲置连接列表。默认值是true。

如果需要使用异步连接回收,这个标记是必须的。

这个标记确保线程取得连接的顺序和他们调用getConnection方法的顺序是相同的。

在性能测试中,这个标记对锁和锁等待有非常大的影响。当fairQueue=true,将有一个依赖于操作系统的线程作为决定线程。如果是Linux系统(系统属性os.name=Linux)。可以在线程池的类加载之前设置系统属性 org.apache.tomcat.jdbc.pool.FairBlockingQueue.ignoreOS=true关闭Linux特定行为但仍然使用公平队列) **杜天微注:这里好像有句话没说完?不同系统有什么不同行为?

Set to true if you wish that calls to getConnectionshould be treated fairly in a true FIFO fashion. This uses the org.apache.tomcat.jdbc.pool.FairBlockingQueue implementation for the list of the idle connections.The default value is true. This flag is required whenyou want to use asynchronous connection retrieval.
Setting this flag ensures that threads receive connections in the order theyarrive.
During performance tests, there is a very large difference in how locks andlock waiting is implemented. When fairQueue=true there isa decision making process based on what operating system the system isrunning. If the system is running on Linux (property os.name=Linux. To disable this Linux specific behavior and still use the fair queue,simply add the property org.apache.tomcat.jdbc.pool.FairBlockingQueue.ignoreOS=true to your system properties before the connection poolclasses are loaded.

abandonWhenPercentageFull

(int) Connections that have been abandoned (timedout) wont get closed and reported up unless the number of connections in useare above the percentage defined by abandonWhenPercentageFull. The value should be between 0-100. The default value is 0, which implies that connections are eligible for closure as soon as removeAbandonedTimeout has been reached.

maxAge

(long) Time in milliseconds to keep this connection.When a connection is returned to the pool, the pool will check to see if the now - time-when-connected> maxAge has been reached, and if so,it closes the connection rather than returning it to the pool. The defaultvalue is 0, which implies that connections will be left open andno age check will be done upon returning the connection to the pool.

useEquals

(boolean) Set to true if you wish the ProxyConnection class to use String.equals and setto false when you wish to use == when comparingmethod names. This property does not apply to added interceptors as those areconfigured individually. The default value is true.

suspectTimeout

(int) Timeout value in seconds. Default value is 0.
Similar to to the removeAbandonedTimeout value but instead of treating the connection asabandoned, and potentially closing the connection, this simply logs thewarning if logAbandoned is set to true. If this value is equal or less than 0,no suspect checking will be performed. Suspect checking only takes place ifthe timeout value is larger than 0 and the connection was not abandoned or ifabandon check is disabled. If a connection is suspect a WARN message getslogged and a JMX notification gets sent once.

rollbackOnReturn

(boolean) If autoCommit==false then the pool can terminate the transaction by calling rollback on theconnection as it is returned to the pool Default value is false.

commitOnReturn

(boolean) If autoCommit==false then the pool can complete the transaction by calling commit on theconnection as it is returned to the pool If rollbackOnReturn==true then this attribute is ignored. Default value is false.

alternateUsernameAllowed

(boolean) By default, the jdbc-pool will ignore the DataSource.getConnection(username,password)call, and simply return a previously pooled connection under the globallyconfigured properties username and password, for performance reasons. The pool can however be usedwith different credentials each time a connection is used. Should you requesta connection with the credentials user1/password1 and the connection waspreviously connected using user2/password2, the connection will be closed,and reopened with the requested credentials. This way, the pool size is stillmanaged on a global level, and not on a per schema level. To enable thefunctionality described in the DataSource.getConnection(username,password)call, simply set the property alternateUsernameAllowed to true.
The default value is false.
This property was added as an enhancement to bug 50025.

dataSource

(javax.sql.DataSource) Inject a data source to theconnection pool, and the pool will use the data source to retrieveconnections instead of establishing them using the java.sql.Driver interface. This is useful when you wish to pool XA connections orconnections established using a data source instead of a connection string.Default value is null

dataSourceJNDI

(String) The JNDI name for a data source to belooked up in JNDI and then used to establish connections to the database. Seethe dataSource attribute. Default value is null

useDisposableConnectionFacade

(boolean) Set this to true if you wish to put afacade on your connection so that it cannot be reused after it has beenclosed. This prevents a thread holding on to a reference of a connection ithas already called closed on, to execute queries on it. Default value is true.

logValidationErrors

(boolean) Set this to true to log errors during thevalidation phase to the log file. If set to true, errors will be logged asSEVERE. Default value is false for backwards compatibility.

propagateInterruptState

(boolean) Set this to true to propagate theinterrupt state for a thread that has been interrupted (not clearing theinterrupt state). Default value is false for backwardscompatibility.

 

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-332286-1-1.html 上篇帖子: Tomcat性能调整(1) 下篇帖子: 解读tomcat(二):tomcat是如何启动的?
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表