文章目录

    • 一、 Basic Pool Configuration (基础配置项)
    • 二、Managing Pool Size and Connection Age (管理连接池大小和连接寿命)
    • 三、Configuring Connection Testing(配置连接测试)
    • 四、Configuring Statement Pooling
    • 五、Configuring Recovery From Database Outages(从数据库中断恢复配置项)
    • 六、Configuring Unresolved Transaction Handling[![Go To Top](https://img-blog.csdnimg.cn/img_convert/559514564b425b8a2d8d410f07ccb293.png)](https://www.mchange.com/projects/c3p0/#contents)
    • 七、Configuring to Debug and Workaround Broken Client Applications[[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-q6948Dkg-1655893008212)(https://www.mchange.com/projects/c3p0/arrow_sm.png)]](https://www.mchange.com/projects/c3p0/#contents)
    • 八、Configuring To Avoid Memory Leaks On Hot Redeploy Of Clients[![Go To Top](https://img-blog.csdnimg.cn/img_convert/559514564b425b8a2d8d410f07ccb293.png)](https://www.mchange.com/projects/c3p0/#contents)
    • 九、Other DataSource Configuration[![Go To Top](https://img-blog.csdnimg.cn/img_convert/559514564b425b8a2d8d410f07ccb293.png)](https://www.mchange.com/projects/c3p0/#contents)
    • 十、Configuring Logging
  • 十一、附录A Appendix A: Configuration Properties[[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vvz8DFQk-1655893008216)(https://www.mchange.com/projects/c3p0/arrow_sm.png)]](https://www.mchange.com/projects/c3p0/#contents)
    • JavaBeans-style Properties[[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9TAOXV1H-1655893008217)(https://www.mchange.com/projects/c3p0/arrow_sm.png)]](https://www.mchange.com/projects/c3p0/#contents)
  • 十二、网络闪断c3p0线程堵塞解决方法

一、 Basic Pool Configuration (基础配置项)

c3p0 Connection pools are very easy to configure via the following basic parameters:

  • acquireIncrement
  • initialPoolSize
  • maxPoolSize
  • maxIdleTime
  • minPoolSize

initialPoolSize, minPoolSize, maxPoolSize define the number of Connections that will be pooled. Please ensure that minPoolSize <= maxPoolSize. Unreasonable values of initialPoolSize will be ignored, and minPoolSize will be used instead.(一旦initialPoolSize 设置的不合理,minPoolSize会去替代它)

Within the range between minPoolSize and maxPoolSize, the number of Connections in a pool varies according to usage patterns. The number of Connections increases whenever a Connection is requested by a user, no Connections are available, and the pool has not yet reached maxPoolSize in the number of Connections managed.(使用连接的数量会增加,知道达到maxPoolSize

Since Connection acquisition is very slow, it is almost always useful to increase the number of Connections eagerly, in batches, rather than forcing each client to wait for a new Connection to provoke a single acquisition when the load is increasing. acquireIncrement determines how many Connections a c3p0 pool will attempt to acquire when the pool has run out of Connections. (Regardless of acquireIncrement, the pool will never allow maxPoolSize to be exceeded.)

(批量创建连接的数量acquireIncrement

The number of Connections in a pool decreases whenever a pool tests a Connection and finds it to be broken (see Configuring Connection Testing below), or when a Connection is expired by the pool after sitting idle for a period of time, or for being too old (See Managing Pool Size and Connection Age.)

(池中连接数减少原因,1. 池连接测试发现连接已经broken,这个可以通过连接测试配置项进行配置。 2. 池中连接已经expired,在空闲周期检查的时候发现,3. 连接已经too old,个人认为,这个连接创建的时间太长了)

二、Managing Pool Size and Connection Age (管理连接池大小和连接寿命)

Different applications have different needs with regard to trade-offs between performance, footprint, and reliability. (不同的应用程序在权衡性能、占用空间和可靠性方面有不同的需求)C3P0 offers a wide variety of options for controlling how quickly pools that have grown large under load revert to minPoolSize, and whether “old” Connections in the pool should be proactively replaced to maintain their reliablity.(C3P0提供了各种各样的选项来控制在负载下增长较大的池恢复到minPoolSize的速度,以及是否应该主动替换池中的“旧”连接以保持其可靠性。)

  • maxConnectionAge
  • maxIdleTime
  • maxIdleTimeExcessConnections

By default, pools will never expire Connections. If you wish Connections to be expired over time in order to maintain “freshness”, set maxIdleTime and/or maxConnectionAge. maxIdleTime defines how many seconds a Connection should be permitted to go unused before being culled from the pool. maxConnectionAge forces the pool to cull any Connections that were acquired from the database more than the set number of seconds in the past.默认情况下,池永远不会使连接过期。如果你希望连接随时间过期以保持“新鲜度”,设置maxIdleTime或者maxConnectionAge。maxIdleTime定义了一个连接在未被使用的情况下可以维持的秒数。maxConnectionAge强制池剔除超过设置时间的所有连接。

maxIdleTimeExcessConnections is about minimizing the number of Connections held by c3p0 pools when the pool is not under load. By default, c3p0 pools grow under load, but only shrink if Connections fail a Connection test or are expired away via the parameters described above. Some users want their pools to quickly release unnecessary Connections after a spike in usage that forces a large pool size. You can achieve this by setting maxIdleTimeExcessConnections to a value much shorter than maxIdleTime, forcing Connections beyond your set minimum size to be released if they sit idle for more than a short period of time.maxIdleTimeExcessConnections是关于最小化c3p0池在无负载剔除连接的时间。默认情况下,c3p0池的连接在有并发负载的情况下才会增长,但只有在连接测试失败或通过上述参数过期时才会减少连接。一些用户希望他们的池在使用高峰后迅速释放不必要的连接。你可以通过设置maxIdleTimeExcessConnections为比maxIdleTime短得多的值来实现这一点,如果空闲时间超过设置的最小大小,则强制释放超出设置的最小值的连接

Some general advice about all of these timeout parameters: Slow down! The point of Connection pooling is to bear the cost of acquiring a Connection only once, and then to reuse the Connection many, many times. Most databases support Connections that remain open for hours at a time. There’s no need to churn through all your Connections every few seconds or minutes. Setting maxConnectionAge or maxIdleTime to 1800 (30 minutes) is quite aggressive. For most databases, several hours may be more appropriate. You can ensure the reliability of your Connections by testing them, rather than by tossing them. (see Configuring Connection Testing.) The only one of these parameters that should generally be set to a few minutes or less is maxIdleTimeExcessConnections.关于所有这些超时参数的一些一般性建议:仔细想想,连接池的意义在于只承担一次获取连接的成本,然后重用连接很多很多次。大多数数据库支持数据库连接被打开几个小时。所以就没有必要每隔几秒或几分钟就翻遍所有的连接。将maxConnectionAgemaxIdleTime设置为1800(30分钟)是相当激进的。对于大多数数据库,几个小时可能更合适。您可以通过测试来确保连接的可靠性,而不是通过丢弃连接,强调通过测试来判定连接是否应该释放掉

三、Configuring Connection Testing(配置连接测试)

c3p0 can be configured to test the Connections that it pools in a variety of ways, to minimize the likelihood that your application will see broken or “stale” Connections.C3P0有很多种配置方式来剔除坏链接和无效连接。 Pooled Connections can go bad for a variety of reasons – some JDBC drivers intentionally “time-out” long-lasting database Connections; back-end databases or networks sometimes go down “stranding” pooled Connections; and Connections can simply become corrupted over time and use due to resource leaks, driver bugs, or other causes. 连接池可能会因为各种原因而变坏,比如说,1.一些JDBC驱动程序故意让长期存在的数据库连接“超时”;2. 后端数据库或网络有时会“搁浅”池连接;3. 或者随着时间的推移,由于资源泄漏、驱动程序bug或其他原因,连接可能会被损坏。

c3p0 provides users a great deal of flexibility in testing Connections, via the following configuration parameters:

  • automaticTestTable
  • connectionTesterClassName
  • idleConnectionTestPeriod
  • preferredTestQuery
  • testConnectionOnCheckin
  • testConnectionOnCheckout

idleConnectionTestPeriod, testConnectionOnCheckout, and testConnectionOnCheckin control when Connections will be tested.这三个参数是控制什么时候连接被测试的,空闲周期测试,取出时测试,归还时测试。 automaticTestTable, connectionTesterClassName, and preferredTestQuery control how they will be tested. 这三个参数是控制怎么测试的。

When configuring Connection testing, first try to minimize the cost of each test. If you are using a JDBC driver that you are certain supports the new(ish) jdbc4 API — and if you are using c3p0-0.9.5 or higher! — let your driver handle this for you. jdbc4 Connections include a method called isValid() that should be implemented as a fast, reliable Connection test. By default, c3p0 will use that method if it is present.为了控制测试成本,可以确认一下你的数据库驱动是否是JDBC4的API,而且您使用C3P0的版本高于或等于c3p0-0.9.5!可以使用驱动来直接进行测试,使用连接API isValid(),其实C3P0也是默认使用这个接口来检查连接的有效性。

However, if your driver does not support this new-ish API, c3p0’s default behavior is to test Connections by calling the getTables() method on a Connection’s associated DatabaseMetaData object. This has the advantage of being very robust and working with any database, regardless of the database schema. However, a call to DatabaseMetaData.getTables() is often much slower than a simple database query, and using this test may significantly impair your pool’s performance.但是,如果你的驱动程序不支持这个新的API, c3p0的默认行为是通过调用一个连接的相关DatabaseMetaData对象的getTables()方法来测试连接。这样做的优点是非常健壮,可以使用任何数据库,而不用考虑数据库模式。但是,对DatabaseMetaData.getTables()的调用通常比简单的数据库查询要慢得多,并且使用此测试可能会显著降低池的性能。

The simplest way to speed up Connection testing under a JDBC 3 driver (or a pre-0.9.5 version of c3p0) is to define a test query with the preferredTestQuery parameter. Be careful, however. Setting preferredTestQuery will lead to errors as Connection tests fail if the query target table does not exist in your database prior to initialization of your DataSource. Depending on your database and JDBC driver, a table-independent query like SELECT 1 may (or may not) be sufficient to verify the Connection. If a table-independent query is not sufficient, instead of preferredTestQuery, you can set the parameter automaticTestTable. Using the name you provide, c3p0 will create an empty table, and make a simple query against it to test the database. 在JDBC 3驱动程序(或c3p0的0.9.5以前版本)下加快Connection测试的最简单方法是使用preferredTestQuery 参数定义一个测试查询。然而,要注意。设置preferredTestQuery将会导致错误,因为如果在DataSource初始化之前,数据库中不存在查询目标表,则连接测试将失败。根据数据库和JDBC驱动程序的不同,像SELECT 1这样与表无关的查询可能(也可能不)足以验证Connection。如果表无关的查询还不够,可以设置参数 automaticTestTable,而不是preferredTestQuery。使用您提供的名称,c3p0将创建一个空表,并对其进行简单查询以测试数据库。

The most reliable time to test Connections is on check-out. But this is also the most costly choice from a client-performance perspective. Most applications should work quite reliably using a combination of idleConnectionTestPeriod and testConnectionOnCheckin. Both the idle test and the check-in test are performed asynchronously, which can lead to better performance, both perceived and actual.测试Connections最可靠的时间是在checkout时。但从客户端性能的角度来看,这也是成本最高的选择。大多数应用程序应该使用idleConnectionTestPeriodtestConnectionOnCheckin的组合非常可靠地工作。空闲测试和签入测试都是异步执行的,这可以带来更好的性能,无论是感知上的还是实际上的

For some applications, high performance is more important than the risk of an occasional database exception. In its default configuration, c3p0 does no Connection testing at all. Setting a fairly long idleConnectionTestPeriod, and not testing on checkout and check-in at all is an excellent, high-performance approach.对于某些应用程序,高性能比偶尔发生数据库异常的风险更重要。在默认配置中,c3p0根本不进行连接测试。设置一个相当长时间的idleConnectionTestPeriod,并且完全不测试签出和签入是一种优秀的高性能方法。

It is possible to customize how c3p0’s DefaultConnectionTester tests when no preferredTestQuery or automaticTestTable are available. Please see Configuring DefaultConnectionTester.isValidTimeout and Configuring DefaultConnectionTester.QuerylessTestRunner. 当没有preferredTestQuery或automaticTestTable可用时,可以定制c3p0的DefaultConnectionTester测试方式

Advanced users may define any kind of Connection testing they wish, by implementing a ConnectionTester and supplying the fully qualified name of the class as connectionTesterClassName. If you’d like your custom ConnectionTesters to honor and support the preferredTestQuery and automaticTestTable parameters, implement UnifiedConnectionTester, most conveniently by extending AbstractConnectionTester. See the api docs for more information.

高级用户可以通过实现 ConnectionTester 接口并提供类的完全限定名称connectionTesterClassName来定义他们想要的任何类型的连接测试。如果您希望您的自定义connectiontester尊重并支持preferredTestQuery和automaticTestTable参数,那么通过扩展AbstractConnectionTester最方便地实现UnifiedConnectionTester。

If you know you want to use the jdbc4 Connection.isValid() method, but you want to set a timeout, consider writing a trivial extension of IsValidConnectionTester. 如果您知道您想使用jdbc4 Connection.isValid()方法,但是您想设置超时,那么可以考虑编写一个简单的 IsValidConnectionTester扩展。

package com.mchange.v2.c3p0.example;
import com.mchange.v2.c3p0.util.IsValidOnlyConnectionTester;
public final class IsValidOnlyConnectionTester30 extends IsValidOnlyConnectionTester {
protected int getIsValidTimeout() { return 30; }
}

Simple advice on Connection testing

  1. If you know your driver supports the JDBC 4 Connection.isValid(...) method and you are using c3p0-0.9.5 or above, don’t set a preferredTestQuery. If your driver does not support this method (or if you are not sure), try **SELECT 1** for your preferredTestQuery, if you are running MySQL or Postgres. For other databases, look for suggestions here. Leave automatedTestTable undefined.如果您的驱动支持JDBC 4 Connection.isValid(...),而且您是使用c3p0-0.9.5或者以上的版本,就不用设置 preferredTestQuery参数了。但是如果您不确认,或者您的驱动不支持,您可以设置参数preferredTestQuery,或者收您是使用 MySQL or Postgres。如果是使用其他的数据库类型,查阅一下suggestions here。且参数automatedTestTable 未定义.

  2. Begin by setting testConnectionOnCheckout to true and get your application to run correctly and stably. If you are happy with your application’s performance, you can stop here! This is the simplest, most reliable form of Connection-testing, but it does have a client-visible performance cost. 设置参数testConnectionOnCheckout的值为true 而且让您的应用程序正确而稳定地运行,如果满意当前您应用的性能表现,那就这样设置,这是最简单的,最有效的连接测试,但是他会导致应用程序的访问性能下降,毕竟每次获取连接都要执行一次测试

  3. If you’d like to improve performance by eliminating Connection testing from clients’ code path:

    a. Set testConnectionOnCheckout to false

    b. Set testConnectionOnCheckin to true

    c. Set idleConnectionTestPeriod to 30, fire up you application and observe. This is a pretty robust setting, all Connections will tested on check-in and every 30 seconds thereafter while in the pool. Your application should experience broken or stale Connections only very rarely, and the pool should recover from a database shutdown and restart quickly. But there is some overhead associated with all that Connection testing.需要启动应用并进行观察,这是一个非常健壮的设置,所有连接将在签入时测试,此后在池中每30秒测试一次。您的应用程序很少会遇到连接中断或失效的情况,数据库池应该在数据库关闭后恢复并快速重启。但是所有的连接测试都有一些开销。

    d. If database restarts will be rare so quick recovery is not an issue, consider reducing the frequency of tests by idleConnectionTestPeriod to, say, 300, and see whether clients are troubled by stale or broken Connections. If not, stick with 300, or try an even bigger number. Consider setting testConnectionOnCheckin back to false to avoid unnecessary tests on checkin. Alternatively, if your application does encounter bad Connections, consider reducing idleConnectionTestPeriod and set testConnectionOnCheckin back to true. There are no correct or incorrect values for these parameters: you are trading off overhead for reliability in deciding how frequently to test. The exact numbers are not so critical. It’s usually easy to find configurations that perform well. It’s rarely worth spending time in pursuit of “optimal” values here.如果您的数据库很少重启,那么快速恢复就不是一个关键问题,那么考虑将idleConnectionTestPeriod的测试频率降低到(比方说)300,并查看客户机是否受到陈旧或中断的连接的困扰。如果没有,那就坚持300,或者尝试一个更大的数字。考虑将testConnectionOnCheckin设置为false,以避免对签入进行不必要的测试。或者,如果你的应用程序遇到坏的连接,考虑减少idleConnectionTestPeriod并将testConnectionOnCheckin设置为true。这些参数没有绝对正确或绝对不正确的值,因此在决定测试频率时,您要权衡开销和可靠性。具体数字并不那么关键。通常很容易找到性能良好的配置。在这里,花时间去追求“最佳”值是不值得的。

So, when should you stick with simple and reliable (Step 2 above), and when is it worth going for better performance (Step 3)? In general, it depends on how much work clients typically do with Connections once they check them out. If clients usually make complex queries and/or perform multiple operations, adding the extra cost of one fast test per checkout will not much affect performance. But if your application typically checks out a Connection and performs one simple query with it, throwing in an additional test can really slow things down.那么,什么时候应该坚持简单可靠(上面的第2步),什么时候值得追求更好的性能(第3步)?一般来说,这取决于客户端在签出Connections后通常使用Connections做多少工作。如果客户端通常执行复杂的查询和/或多个操作,那么增加每次签出一次快速测试的额外成本不会对性能造成太大影响。但是,如果您的应用程序通常检出一个Connection并使用它执行一个简单的查询,那么添加额外的测试确实会降低速度。

That’s nice in theory, but often people don’t really have a good sense of how much work clients perform on average. The best thing to do is usually to try Step 3, see if it helps (however you measure performance), see if it hurts (is your application troubled by broken Connections? does it recover from database restarts well enough?), and then decide. You can always go back to simple, slow, and robust. Just set testConnectionOnCheckout to true, testConnectionOnCheckin to false, and set idleConnectionTestPeriod to 0. 这在理论上是不错的,但通常人们并不真正清楚客户平均完成多少工作。最好的做法通常是尝试步骤3,看看它是否有帮助(无论您如何衡量性能),看看它是否有害(您的应用程序是否受到连接中断的困扰?从数据库重新启动恢复是否足够好?),然后决定。你总是可以回到简单、缓慢和强健的状态。只需将testConnectionOnCheckout设置为true, testConnectionOnCheckin设置为false,并将idleConnectionTestPeriod设置为0。

But do, always, be sure that your tests themselves are performant, either because your JDBC driver supports Connection.isValid(...) or because you have set an efficient preferredTestQuery !!!但是,一定要确保您的测试本身是有效果的,或者您的JDBC驱动程序支持Connection.isValid(…),或者因为您设置了一个有效的preferredTestQuery !!。

四、Configuring Statement Pooling

c3p0 implements transparent PreparedStatement pooling as defined by the JDBC spec. Under some circumstances, statement pooling can dramatically improve application performance. Under other circumstances, the overhead of statement pooling can slightly harm performance. Whether and how much statement pooling will help depends on how much parsing, planning, and optimizing of queries your databases does when the statements are prepared. Databases (and JDBC drivers) vary widely in this respect. It’s a good idea to benchmark your application with and without statement pooling to see if and how much it helps.c3p0实现了JDBC规范定义的透明PreparedStatement池。在某些情况下,语句池可以显著提高应用程序的性能。在其他情况下,语句池的开销可能会略微损害性能。语句池是否有帮助以及有多大帮助,取决于准备语句时数据库对查询的解析、规划和优化程度。数据库(和JDBC驱动程序)在这方面差别很大。对使用和不使用语句池的应用程序进行基准测试是一个好主意,看看它是否有帮助以及有多大帮助。

You configure statement pooling in c3p0 via the following configuration parameters:

  • maxStatements
  • maxStatementsPerConnection
  • statementCacheNumDeferredCloseThreads

maxStatements is JDBC’s standard parameter for controlling statement pooling. maxStatements defines the total number PreparedStatements a DataSource will cache. The pool will destroy the least-recently-used PreparedStatement when it hits this limit. This sounds simple, but it’s actually a strange approach, because cached statements conceptually belong to individual Connections; they are not global resources. To figure out a size for maxStatements that does not “churn” cached statements, you need to consider the number of frequently used PreparedStatements in your application, and multiply that by the number of Connections you expect in the pool (maxPoolSize in a busy application).maxStatements 是JDBC控制语句池的标准参数。maxStatements定义了数据源将缓存的PreparedStatements的总数。当达到这个限制时,池将销毁最近最少使用的PreparedStatement。这听起来很简单,但实际上是一种奇怪的方法,因为缓存语句在概念上属于各个连接;它们不是全局资源。要计算出不“占用”缓存语句的maxStatements的大小,你需要考虑应用程序中频繁使用 preparedstatement的数量,并将其乘以池中预期的连接数(繁忙应用程序中的maxPoolSize)。

maxStatementsPerConnection is a non-standard configuration parameter that makes a bit more sense conceptually. It defines how many statements each pooled Connection is allowed to own. You can set this to a bit more than the number of PreparedStatements your application frequently uses, to avoid churning.maxStatementsPerConnection是一个非标准配置参数,它在概念上更有意义。它定义了每个连接池允许拥有多少条语句。您可以将其设置为比应用程序经常使用的preparedstatement数量多一点,以避免重复使用。

If either of these parameters are greater than zero, statement pooling will be enabled. If both parameters are greater than zero, both limits will be enforced. If only one is greater than zero, statement pooling will be enabled, but only one limit will be enforced.

如果这些参数中的任何一个大于零,则将启用语句池。如果两个参数都大于零,则两个限制都将执行。如果只有一个大于0,则将启用语句池,但只执行一个限制。

If statementCacheNumDeferredCloseThreads is greater than zero, the Statement pool will defer physically close()ing cached Statements until its parent Connection is not in use by any client or internally (in e.g. a test) by the pool itself. For some JDBC drivers (especially Oracle), attempts to close a Statement freeze if the parent Connection is in use. This parameter defaults to 0. Set it to a positive value if you observe “APPARENT DEADLOCKS” realted to Connection close tasks. Almost always, that value should be one: if you need more than one Thread dedicated solely to Statement destruction, you probably should set maxStatements and/or maxStatementsPerConnection to higher values so you don’t churn through cached Statements so quickly.如果statementCacheNumDeferredCloseThreads大于0,语句池将物理上延迟关闭()缓存语句,直到父连接没有被任何客户端使用,或者池本身内部(例如测试)没有使用。对于某些JDBC驱动程序(尤其是Oracle),如果父连接正在使用,则尝试关闭Statement冻结。该参数默认为0。如果观察到与连接关闭任务相关的 “APPARENT DEADLOCKS”,则将其设置为正值。基本上,这个值应该是1:如果您需要多个线程专门用于语句销毁,您可能应该将maxStatements和/或maxStatementsPerConnection设置为更高的值,这样您就不会这么快地使用缓存的语句。

五、Configuring Recovery From Database Outages(从数据库中断恢复配置项)

c3p0 DataSources are designed (and configured by default) to recover from temporary database outages, such as those which occur during a database restart or brief loss of network connectivity. You can affect how c3p0 handles errors in acquiring Connections via the following configurable properties:c3p0数据源被设计(并在默认情况下配置)用于从临时数据库中断中恢复,例如在数据库重启或网络连接短暂中断期间发生的中断。你可以通过以下可配置属性来影响c3p0如何处理获取连接时的错误:

  • acquireRetryAttempts
  • acquireRetryDelay
  • breakAfterAcquireFailure

When a c3p0 DataSource attempts and fails to acquire a Connection, it will retry up to acquireRetryAttempts times, with a delay of acquireRetryDelay between each attempt. If all attempts fail, any clients waiting for Connections from the DataSource will see an Exception, indicating that a Connection could not be acquired. Note that clients do not see any Exception until a full round of attempts fail, which may be some time after the initial Connection attempt. If acquireRetryAttempts is set to 0, c3p0 will attempt to acquire new Connections indefinitely, and calls to getConnection() may block indefinitely waiting for a successful acquisition.当c3p0数据源尝试获取连接失败时,它将重试到acquireRetryAttempts次,每次尝试之间的延迟为acquireRetryDelay。如果所有尝试都失败,任何等待来自数据源的连接的客户端将看到一个Exception,表明无法获得连接。请注意,客户端在整个尝试失败之前不会看到任何异常,这可能是在初始连接尝试之后的一段时间。如果acquireRetryAttempts设置为0,c3p0将尝试无限地获取新的连接,并且调用’getConnection() 可能会无限地阻塞,直至成功的获取连接。

Once a full round of acquisition attempts fails, there are two possible policies. By default, the c3p0 DataSource will remain active, and will try again to acquire Connections in response to future requests for Connections. If you set breakAfterAcquireFailure to true, the DataSource will consider itself broken after a failed round of Connection attempts, and future client requests will fail immediately.一旦一轮尝试失败,有两种可能的策略。默认情况下,c3p0数据源将保持活动状态,并将再次尝试获取连接,以响应未来的连接请求。但是如果您将breakAfterAcquireFailure设置为’true ,那么数据源将在连接尝试失败一轮后认为自己已经中断,并且以后的客户端请求也将立即失败。

Note that if a database restart occurs, a pool may contain previously acquired but now stale Connections. By default, these stale Connections will only be detected and purged lazily, when an application attempts to use them, and sees an Exception. Setting maxIdleTime or maxConnectionAge can help speed up the replacement of broken Connections. (See Managing ConnectionAge.) If you wish to avoid application Exceptions entirely, you must adopt a connection testing strategy that is likely to detect stale Connections prior to their delivery to clients. (See “Configuring Connection Testing”.) Even with active Connection testing (testConnectionOnCheckout set to true, or testConnectionOnCheckin and a short idleConnectionTestPeriod), your application may see occasional Exceptions on database restart, for example if the restart occurs after a Connection to the database has already been checked out.注意,如果数据库重新启动,池中可能包含以前获取但现在失效的连接。默认情况下,只有当应用程序试图使用这些陈旧的连接并看到一个Exception时,才会惰性地检测和清除这些连接。设置maxIdleTimemaxConnectionAge 可以帮助加速替换坏掉的连接。(见[管理ConnectionAge] (https://www.mchange.com/projects/c3p0/ managing_pool_size))。如果希望完全避免应用程序异常,则必须采用连接测试策略,该策略可能会在交付给客户端之前检测失效的连接。(请参阅“配置连接测试”。)即使活动连接测试(testConnectionOnCheckout设置为“真正的”,或testConnectionOnCheckin和一个简短的idleConnectionTestPeriod),对数据库重新启动您的应用程序可能会看到偶尔例外,例如,如果重启后出现数据库连接已被检出。

六、Configuring Unresolved Transaction Handling

Connections checked into a pool cannot have any unresolved transactional work associated with them. If users have set autoCommit to false on a Connection, and c3p0 cannot guarantee that there is no pending transactional work, c3p0 must either rollback() or commit() on check-in (when a user calls close()). The JDBC spec is (unforgivably) silent on the question of whether unresolved work should be committed or rolled back on Connection close. By default, c3p0 rolls back unresolved transactional work when a user calls close().

You can adjust this behavior via the following configuration properties:

If you wish c3p0 to allow unresolved transactional work to commit on checkin, set autoCommitOnClose to true. If you wish c3p0 to leave transaction management to you, and neither commit nor rollback (nor modify the state of Connection autoCommit), you may set forceIgnoreUnresolvedTransactions to true. Setting forceIgnoreUnresolvedTransactions is strongly discouraged, because if clients are not careful to commit or rollback themselves prior to close(), or do not set Connection autoCommit consistently, bizarre unreproduceable behavior and database lockups can occur.

七、Configuring to Debug and Workaround Broken Client Applications[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-q6948Dkg-1655893008212)(https://www.mchange.com/projects/c3p0/arrow_sm.png)]

Sometimes client applications are sloppy about close()ing all Connections they check out. Eventually, the pool grows to maxPoolSize, and then runs out of Connections, because of these bad clients.

有时候,应用程序在使用close()的动作去归还检出的连接过于草率会很容易导致连接池连接增长到最大设置,并导致连接溢出。

The right way to address this problem is to fix the client application. c3p0 can help you debug, by letting you know where Connections are checked out that occasionally don’t get checked in. In rare and unfortunate situations, development of the client application is closed, and even though it is buggy, you cannot fix it. c3p0 can help you work around the broken application, preventing it from exhausting the pool.

解决这个问题的正确方法是修复客户机应用程序。c3p0可以帮助您调试,通过让您知道在哪里连接被检查出来,且不被检入。在罕见和不幸的情况下,客户端应用程序的开发是关闭的,即使它有缺陷,您也无法修复它。C3p0可以帮助您处理损坏的应用程序,防止它耗尽连接池连接。

The following parameters can help you debug or workaround broken client applications.

unreturnedConnectionTimeout defines a limit (in seconds) to how long a Connection may remain checked out. If set to a nozero value, unreturned, checked-out Connections that exceed this limit will be summarily destroyed, and then replaced in the pool. Obviously, you must take care to set this parameter to a value large enough that all intended operations on checked out Connections have time to complete. You can use this parameter to merely workaround unreliable client apps that fail to close() Connections.

有时候,应用程序在使用close()的动作去归还检出的连接过于草率会很容易导致连接池连接增长到最大设置,并导致连接溢出。如果设置为非零值,超过此限制的未返回的签出连接将被立即销毁,然后在池中替换。显然,您必须小心地将该参数设置为足够大的值,使签出的连接上的所有预期操作都有时间完成。您可以使用此参数来解决不可靠的客户端应用程序无法关闭()连接的问题。

Much better than working-around is fixing. If, in addition to setting unreturnedConnectionTimeout, you set debugUnreturnedConnectionStackTraces to true, then a stack trace will be captured each time a Connection is checked-out. Whenever an unreturned Connection times out, that stack trace will be printed, revealing where a Connection was checked out that was not checked in promptly. debugUnreturnedConnectionStackTraces is intended to be used only for debugging, as capturing a stack trace can slow down Connection check-out.

有时候,应用程序在使用close()的动作去归还检出的连接过于草率会很容易导致连接池连接增长到最大设置,并导致连接溢出。如果除了设置’ unreturnedConnectionTimeout ‘之外,还将’ debugUnreturnedConnectionStackTraces ‘设为’ true ‘,那么每次签出一个Connection时,都会捕获一个堆栈跟踪。每当未返回的Connection超时时,将打印该堆栈跟踪,显示未及时签入的Connection签出的位置。’ debugUnreturnedConnectionStackTraces '只用于调试,因为捕获堆栈跟踪会减慢连接检出的速度。

八、Configuring To Avoid Memory Leaks On Hot Redeploy Of Clients

c3p0 spawns a variety of Threads (helper threads, java.util.Timer threads), and does so lazily in response to the first client request experienced by a PooledDataSource. By default, the Threads spawned by c3p0 inherit a java.security.AccessControlContext and a contextClassLoader property from this first-calling Thread. If that Thread came from a client that may need to be hot-undeployed, references to these objects may prevent the undeployed application, often partitioned into a ClassLoader, from being garbage collected. (See for example this description of Tomcat memory leaks on redeployment.)

c3p0 provides two configuration parameters that can help with this:

contextClassLoaderSource should be set to one of caller, library, or none. The default (which yields the default behavior described above) is caller. Set this to library to use c3p0’s ClassLoader, so that no reference is maintained to a client that may need to be redeployed.

privilegeSpawnedThreads is a boolean, false by default. Set this to true so that c3p0’s Threads use the the c3p0 library’s AccessControlContext, rather than an AccessControlContext that may be associated with the client application and prevent its garbage collection.

九、Other DataSource Configuration

See Appendix A for information about the following configuration properties:

numHelperThreads and maxAdministrativeTaskTime help to configure the behavior of DataSource thread pools. By default, each DataSource has only three associated helper threads. If performance seems to drag under heavy load, or if you observe via JMX or direct inspection of a PooledDataSource, that the number of “pending tasks” is usually greater than zero, try increasing numHelperThreads. maxAdministrativeTaskTime may be useful for users experiencing tasks that hang indefinitely and “APPARENT DEADLOCK” messages. (See Appendix A for more.)numHelperThreadsmaxAdministrativeTaskTime 帮助配置数据源线程池的行为。默认情况下,每个DataSource只有三个关联的辅助线程。如果性能似乎在重负载下下降,或者如果你通过JMX或直接检查PooledDataSource观察到“挂起的任务”的数量通常大于零,尝试增加numHelperThreadsmaxAdministrativeTaskTime 可能对用户遇到无限挂起的任务和“明显的死锁”消息有用。(详见附录A)

Ordinarily check-ins are performed asynchronously so that clients do not experience the overhead of on-check-in Connection tests and/or operations specified in ConnectionCustomizer.onCheckIn(...). However, asynchronous checkins add to Thread pool congestion. Under loads so large that it is impractical to expand numHelperThreads to reduce congestion, forceSynchronousCheckins will cause client Threads to perform the checkin operations, adding to the load of the Thread pool and precluding any delays in termination of checkin due to Thread pool congestion. As long as you neither perform Connection tests on check-in (see testConnectionOnCheckin) nor perform database operations or other slow work in ConnectionCustomizer.onCheckIn(...), this setting is likely to improve performance. However, if Connections are tested on check-in, or custom work is performed, setting forceSynchronousCheckins will cause clients to experience delays associated with that work when they call Connection.close().通常,check-ins是异步执行的,这样客户端就不会遇到ConnectionCustomizer.onCheckIn(…)中指定的签入连接测试和/或操作的开销。然而,异步签入会增加线程池拥塞。在如此大的负载之下,扩展’ numHelperThreads ‘来减少拥塞是不切实际的,’ forceSynchronousCheckins ‘将导致客户端线程执行签入操作,增加线程池的负载,并减少不了任何由于线程池拥塞而终止签入的延迟。只要您既不在签入时执行连接测试(请参阅testConnectionOnCheckin),也不在ConnectionCustomizer.onCheckIn(…)中执行数据库操作或其他慢速工作,此设置可能会提高性能。然而,如果在签入时测试了连接,或者执行了自定义工作,设置’ forceSynchronousCheckins 将导致客户端在调用Connection.close()时经历与该工作相关的延迟。

checkoutTimeout limits how long a client will wait for a Connection, if all Connections are checked out and one cannot be supplied immediately.

十、Configuring Logging

c3p0 uses a custom logging library similar to jakarta commons-logging. Log messages can be directed to the to the popular slf4j (with its logback backend), to the venerable log4j library, the more recent log4j2 library, to the standard logging facility introduced with jdk1.4, or to System.err. Nearly all configuration should be done at the level of your preferred logging library. There are a very few configuration options specific to c3p0’s logging, and usually the defaults will be fine. Logging-related parameters may be placed in your c3p0.properties file, in HOCON configuration files, in a file called mchange-log.properties at the top-level of your classpath, or they may be defined as System properties. (The logging properties defined below may not be defined in c3p0-config.xml!) See the box below.

C3P0使用了一个自定义日志库,类似于Jakarta common-logging。日志消息可以被定向到流行的slf4j(及其logback后端),到令人尊敬的log4j库,或者最近的log4j2库,或者到jdk1.4引入的标准日志记录工具,或者’ System.err’。几乎所有的配置都应该在首选的日志库级别上完成。c3p0日志记录特有的配置选项非常少,通常默认设置就可以了。与日志相关的参数可以放在您的’ c3p0.properties`文件中。如果是在HOCON配置文件中,那么就是在一个名为“mchange-log.properties”的文件中。或者它们可以被定义为系统属性。(下面定义的日志属性可能没有在’ c3p0-config.xml '中定义!)请参阅下面的框。

c3p0’s logging behavior is affected by certain build-time options. If build-option c3p0.debug is set to false, all messages at a logging level below INFO will be suppressed. Build-option c3p0.trace controls how fine-grained c3p0’s below INFO level reporting will be. For the moment, distributed c3p0 binaries are compiled with debug set to true and trace set to its maximum level of 10. But binaries may eventually be distributed with debug set to false. (For the moment, the performance impact of the logging level-checks seems very small, and it’s most flexible to compile in all the messages, and let your logging library control which are emitted.) When c3p0 starts up, it emits the build-time values of debug and trace, along with the version and build time.

C3p0的日志记录行为受某些构建时选项的影响。如果构建选项c3p0.debug被设置为false,所有日志级别低于INFO的消息将被抑制。构建选项的c3p0.trace控制INFO级别以下c3p0报告的细粒度。目前,分布式c3p0二进制文件在编译时将“debug”设置为“true”,并将“trace”设置为最大等级“10”。但是二进制文件可能最终会在发布时将“debug”设置为“false”。(目前,日志级别检查的性能影响似乎非常小,在所有消息中编译是最灵活的,并让您的日志库进行具体控制)。当c3p0启动时,它会输出调试和跟踪在构建时设定的值,或者以及版本发布时构建的值。

  1. com.mchange.v2.log.MLog

Determines which library c3p0 will output log messages to. By default, if slf4j is available, it will use that library, otherwise log4j if available, otherwise log4j2 if available, otherwise jdk1.4 logging apis, and if all are unavailable, it will fallback to logging via System.err. If you want to directly control which library is used, you may set this property to one of:

  • com.mchange.v2.log.slf4j.Slf4jMLog
  • com.mchange.v2.log.log4j.Log4jMLog
  • com.mchange.v2.log.log4j2.Log4j2MLog
  • com.mchange.v2.log.jdk14logging.Jdk14MLog
  • com.mchange.v2.log.FallbackMLog

Alternatively, the following abbreviations are supported:另外支持一下缩写>

  • slf4j
  • log4j
  • log4j2
  • jul, jdk14, java.util.logging
  • fallback

You may also set this property to a comma separated list of any mix the above alternatives, to define an order of preference among logging libraries.

您还可以将此属性设置为一个逗号分隔的列表,将上述选项混合在一起,以定义日志库之间的首选顺序。

  1. com.mchange.v2.log.MLog.useRedirectableLoggers

Using API in com.mchange.v2.log.MLog, it is possible to change at runtime what library c3p0 output logs to, or to switch midstream to the standard-error based fallback logger. However, for this to be useful, loggers already constructed against the original configuration need to be sensitive to the change. Setting this value to true will cause c3p0 to use slightly less performant loggers that can be redirected between libraries at runtime. This setting is false by default.

使用’ com.mchange.v2.log.MLog '中的API,可以在运行时修改库c3p0输出日志的位置,或在切换到一个基于标准fallback的日志记录器。然而,为了使这一点生效,已经根据原始配置构造的日志记录器要对修改敏感。将该值设置为“true”将导致c3p0使用性能稍差的记录器,这些记录器可以在运行时在库之间重定向。该设置默认为“false”。

  1. com.mchange.v2.log.jdk14logging.suppressStackWalk

Under JDK standard logging, the logging library may inspect stack traces to determine the class and method from which a log message was generated. That can be helpful, but it is also slow. Setting this configuration parameter to true will suppress this stack walk, and reduce the overhead of logging. This property now defaults to true, and logger names are logged in place of class names. To return to the original slower but more informative approach, explicitly set the property to false.

在JDK标准日志记录下,日志库可以检查堆栈跟踪以确定生成日志消息的类和方法。这可能是有帮助的,但也是缓慢的。将此配置参数设置为true将抑制此堆栈遍历,并减少日志记录的开销。**此属性现在默认为’ true ',日志记录器的名称将被记录在类名的位置。**要返回原来的较慢但信息量更大的方法,显式地将属性设置为false。

  1. com.mchange.v2.log.NameTransformer

By default, c3p0 uses very fine-grained logging, in general with one logger for each c3p0 class. For a variety of reasons, some users may prefer fewer, more global loggers. You may opt for one-logger-per-package by setting com.mchange.v2.log.NameTransformer to the value com.mchange.v2.log.PackageNames. Advanced users can also define other strategies for organizing the number and names of loggers by setting this variable to the fully-qualified class name of a custom implementation of the com.mchange.v2.log.NameTransformer interface.

默认情况下,c3p0使用非常细粒度的日志记录,通常为每个c3p0类使用一个日志记录器。由于各种原因,一些用户可能更喜欢更少、更多的全局记录器。您可以通过设置com.mchange.v2.log.NameTransformercom.mchange.v2.log.PackageNames. 。高级用户还可以设置其他自定义策略为继承了接口com.mchange.v2.log.NameTransformer的全限定实现类类名。

  1. com.mchange.v2.log.FallbackMLog.DEFAULT_CUTOFF_LEVEL

If, whether by choice or by necessity, you are using c3p0’s System.err fallback logger, you can use this parameter to control how detailed c3p0’s logging should be. Any of the following values (taken from the jdk1.4 logging library) are acceptable:OFF``SEVERE``WARNING``INFO``CONFIG``FINE``FINER``FINEST``ALLThis property defaults to INFO.

如果,无论是出于选择还是必要,您正在使用c3p0的System.errfallback logger,您可以使用此参数来控制c3p0日志记录的详细程度。以下任何值(取自jdk1.4日志库)都是可以接受的:’ OFF ’ ’ SEVERE ’ ’ WARNING ’ ’ INFO ’ ’ CONFIG ’ ’ FINE ’ ’ FINER ’ ’ FINEST ’ ’ ALL ‘该属性默认为’ INFO '。>

十一、附录A Appendix A: Configuration Properties[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vvz8DFQk-1655893008216)(https://www.mchange.com/projects/c3p0/arrow_sm.png)]

c3p0 configuration properties can be divided into JavaBeans-style Properties and Other Properties.

JavaBeans-style Properties[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9TAOXV1H-1655893008217)(https://www.mchange.com/projects/c3p0/arrow_sm.png)]

The following properties can be set directly in code as JavaBeans properties, via a System properties or a c3p0.properties file (with c3p0. prepended to the property name), in HOCON (typesafe-config) files, or in a c3p0-config.xml file. See the section on Configuration above. Click on the property name for a full description.

acquireIncrement acquireRetryAttempts acquireRetryDelay autoCommitOnClose automaticTestTable breakAfterAcquireFailure checkoutTimeout connectionCustomizerClassName connectionTesterClassName contextClassLoaderSource dataSourceName debugUnreturnedConnectionStackTraces driverClass extensions factoryClassLocation forceIgnoreUnresolvedTransactions forceSynchronousCheckins forceUseNamedDriverClass idleConnectionTestPeriod initialPoolSize jdbcUrl maxAdministrativeTaskTime maxConnectionAge maxIdleTime maxIdleTimeExcessConnections maxPoolSize maxStatements maxStatementsPerConnection minPoolSize numHelperThreads overrideDefaultUser overrideDefaultPassword password preferredTestQuery privilegeSpawnedThreads propertyCycle statementCacheNumDeferredCloseThreads testConnectionOnCheckin testConnectionOnCheckout unreturnedConnectionTimeout user usesTraditionalReflectiveProxies
  • acquireIncrement

    Default: 3

    Determines how many connections at a time c3p0 will try to acquire when the pool is exhausted. [See “Basic Pool Configuration”]

  • acquireRetryAttempts

    Default: 30

    Defines how many times c3p0 will try to acquire a new Connection from the database before giving up. If this value is less than or equal to zero, c3p0 will keep trying to fetch a Connection indefinitely. 如果这个值小于或等于0,c3p0将继续尝试无限获取一个Connection。[See “Configuring Recovery From Database Outages”]

  • acquireRetryDelay

    Default: 1000 Milliseconds,

    time c3p0 will wait between acquire attempts. [See “Configuring Recovery From Database Outages”]

  • autoCommitOnClose

    Default: false

    The JDBC spec is unforgivably silent on what should happen to unresolved, pending transactions on Connection close. C3P0’s default policy is to rollback any uncommitted, pending work. (I think this is absolutely, undeniably the right policy, but there is no consensus among JDBC driver vendors.) Setting autoCommitOnClose to true causes uncommitted pending work to be committed, rather than rolled back on Connection close. [Note: Since the spec is absurdly unclear on this question, application authors who wish to avoid bugs and inconsistent behavior should ensure that all transactions are explicitly either committed or rolled-back before close is called.] [See “Configuring Unresolved Transaction Handling”]

  • automaticTestTable

    Default: null

    If provided, c3p0 will create an empty table of the specified name, and use queries against that table to test the Connection. If automaticTestTable is provided, c3p0 will generate its own test query, therefore any preferredTestQuery set will be ignored. You should not work with the named table after c3p0 creates it; it should be strictly for c3p0’s use in testing your Connection. (If you define your own ConnectionTester, it must implement the QueryConnectionTester interface for this parameter to be useful.) [See “Configuring Connection Testing”]

  • breakAfterAcquireFailure

    Default: false

    If true, a pooled DataSource will declare itself broken and be permanently closed if a Connection cannot be obtained from the database after making acquireRetryAttempts to acquire one. If false, failure to obtain a Connection will cause all Threads waiting for the pool to acquire a Connection to throw an Exception, but the DataSource will remain valid, and will attempt to acquire again following a call to getConnection(). [See “Configuring Recovery From Database Outages”]

    如果为真,在使用“acquireRetryAttempts” 获取连接后,无法从数据库中获取连接,则池化数据源将声明自己已损坏,并永久关闭。如果为false,获取连接失败将导致所有等待池获取连接的线程抛出异常,但数据源将保持有效,并将在调用’ getConnection() '后尝试再次获取。

  • checkoutTimeout

    Default: 0

    The number of milliseconds a client calling getConnection() will wait for a Connection to be checked-in or acquired when the pool is exhausted. Zero means wait indefinitely. Setting any positive value will cause the getConnection() call to time-out and break with an SQLException after the specified number of milliseconds.

    当连接池耗尽时,调用getConnection()的客户端等待连接被签入或获取的毫秒数。零意味着无限期等待。设置任何正值都会导致getConnection()调用超时,并在指定的毫秒数之后以’ SQLException '中断。

  • connectionCustomizerClassName

    Default: null

    The fully qualified class-name of an implememtation of the ConnectionCustomizer interface, which users can implement to set up Connections when they are acquired from the database, or on check-out, and potentially to clean things up on check-in and Connection destruction. If standard Connection properties (holdability, readOnly, or transactionIsolation) are set in the ConnectionCustomizer’s onAcquire() method, these will override the Connection default values.

  • connectionTesterClassName

    Default: com.mchange.v2.c3p0.impl.DefaultConnectionTester

    The fully qualified class-name of an implememtation of the ConnectionTester interface, or QueryConnectionTester if you would like instances to have access to a user-configured preferredTestQuery. This can be used to customize how c3p0 DataSources test Connections, but with the introduction of automaticTestTable and preferredTestQuery configuration parameters, “rolling your own” should be overkill for most users. [See “Configuring Connection Testing”]

  • contextClassLoaderSource

    Default: caller

    Must be one of caller, library, or none. Determines how the contextClassLoader (see java.lang.Thread) of c3p0-spawned Threads is determined. If caller, c3p0-spawned Threads (helper threads, java.util.Timer threads) inherit their contextClassLoader from the client Thread that provokes initialization of the pool. If library, the contextClassLoader will be the class that loaded c3p0 classes. If none, no contextClassLoader will be set (the property will be null), which in practice means the system ClassLoader will be used. The default setting of caller is sometimes a problem when client applications will be hot redeployed by an app-server. When c3p0’s Threads hold a reference to a contextClassLoader from the first client that hits them, it may be impossible to garbage collect a ClassLoader associated with that client when it is undeployed in a running VM. Setting this to library can resolve these issues. [See “Configuring To Avoid Memory Leaks On Hot Redeploy Of Client”]Does Not Support Per-User Overrides.

  • dataSourceName

    Default: if configured with a named config, the config name, otherwise the pool’s “identity token”

    Every c3p0 pooled data source is given a dataSourceName, which serves two purposes. It helps users find DataSources via C3P0Registry, and it is included in the name of JMX mBeans in order to help track and distinguish between multiple c3p0 DataSources even across application or JVM restarts. dataSourceName defaults to the pool’s configuration name, if a named config was used, or else to an “identity token” (an opaque, guaranteed unique String associated with every c3p0 DataSource). You may update this property to any name you find convenient. dataSourceName is not guaranteed to be unique — for example, multiple DataSource created from the same named configuration will share the same dataSourceName. But if you are going to make use of dataSourceName, you will probably want to ensure that all pooled DataSources within your JVM do have unique names.

  • debugUnreturnedConnectionStackTraces

    Default: false

    If true, and if ```unreturnedConnectionTimeoutis set to a positive value, then the pool will capture the stack trace (via an Exception) of all Connection checkouts, and the stack traces will be printed when unreturned checked-out Connections timeout. This is intended to debug applications with Connection leaks, that is applications that occasionally fail to return Connections, leading to pool growth, and eventually exhaustion (when the pool hitsmaxPoolSize` with all Connections checked-out and lost). This parameter should only be set while debugging, as capturing the stack trace will slow down every Connection check-out. [See “Configuring to Debug and Workaround Broken Client Applications”]

  • driverClass

    Default: null

    The fully-qualified class name of the JDBC driverClass that is expected to provide Connections. c3p0 will preload any class specified here to ensure that appropriate URLs may be resolved to an instance of the driver by java.sql.DriverManager. If you wish to skip DriverManager resolution entirely and ensure that an instance of the specified class is used to provide Connections, use ```driverClassin combination withforceUseNamedDriverClass. [See also jdbcUrl`.]Does Not Support Per-User Overrides.

  • extensions

    Default: an empty java.util.Map

    A java.util.Map (raw type) containing the values of any user-defined configuration extensions defined for this DataSource.Does Not Support Per-User Overrides.

  • factoryClassLocation

    Default: null

    DataSources that will be bound by JNDI and use that API’s Referenceable interface to store themselves may specify a URL from which the class capable of dereferencing a them may be loaded. If (as is usually the case) the c3p0 libraries will be locally available to the JNDI service, leave this set as null.

  • forceIgnoreUnresolvedTransactions

    Default: false

    *Strongly disrecommended. Setting this to true may lead to subtle and bizarre bugs.* This is a terrible setting, leave it alone unless absolutely necessary. It is here to workaround broken databases / JDBC drivers that do not properly support transactions, but that allow Connections’ autoCommit flags to go to false regardless. If you are using a database that supports transactions “partially” (this is oxymoronic, as the whole point of transactions is to perform operations reliably and completely, but nonetheless such databases are out there), if you feel comfortable ignoring the fact that Connections with autoCommit == false may be in the middle of transactions and may hold locks and other resources, you may turn off c3p0’s wise default behavior, which is to protect itself, as well as the usability and consistency of the database, by either rolling back (default) or committing (see c3p0.autoCommitOnClose above) unresolved transactions. This should only be set to true when you are sure you are using a database that allows Connections’ autoCommit flag to go to false, but offers no other meaningful support of transactions. Otherwise setting this to true is just a bad idea. [See “Configuring Unresolved Transaction Handling”]

  • forceSynchronousCheckins

    Default: false

    Setting this to true forces Connections to be checked-in synchronously, which under some circumstances may improve performance. Ordinarily Connections are checked-in asynchronously so that clients avoid any overhead of testing or custom check-in logic. However, asynchronous check-in contributes to thread pool congestion, and very busy pools might find clients delayed waiting for check-ins to complete. Expanding numHelperThreads can help manage Thread pool congestion, but memory footprint and switching costs put limits on practical thread pool size. To reduce thread pool load, you can set forceSynchronousCheckins to true. Synchronous check-ins are likely to improve overall performance when testConnectionOnCheckin is set to false and no slow work is performed in a ConnectionCustomizer’s onCheckIn(...) method. If Connections are tested or other slow work is performed on check-in, then this setting will cause clients to experience the overhead of that work on Connection.close(), which you must trade-off against any improvements in pool performance. [See “Other DataSource Configuration”]

    将此设置为true将强制同步签入Connections,这在某些情况下可能会提高性能。通常情况下,连接是异步签入的,这样客户机就可以避免任何测试或自定义签入逻辑的开销。但是,异步签入会导致线程池拥塞,非常繁忙的池可能会发现客户端延迟等待签入完成。扩展numHelperThreads可以帮助管理线程池拥塞,但是内存占用和切换成本限制了实际的线程池大小。为了减少线程池负载,你可以设置forceSynchronousCheckinstrue。当testConnectionOnCheckin设置为false,并且在ConnectionCustomizeronCheckIn(…)方法中不执行缓慢的工作时,同步签入可能会提高整体性能。如果在签入时测试连接或执行其他慢速工作,则此设置将导致客户端在Connection.close()上体验该工作的开销,您必须权衡池性能的任何改进。

  • forceUseNamedDriverClass

    Default: false

    Setting the parameter driverClass causes that class to preload and register with java.sql.DriverManager. However, it does not on its own ensure that the driver used will be an instance of driverClass, as DriverManager may (in unusual cases) know of other driver classes which can handle the specified jdbcUrl. Setting this parameter to true causes c3p0 to ignore DriverManager and simply instantiate driverClass directly.Does Not Support Per-User Overrides.

  • idleConnectionTestPeriod

    Default: 0

    If this is a number greater than 0, c3p0 will test all idle, pooled but unchecked-out connections, every this number of seconds. [See “Configuring Connection Testing”]

  • initialPoolSize

    Default: 3

    Number of Connections a pool will try to acquire upon startup. Should be between minPoolSize and maxPoolSize. [See “Basic Pool Configuration”]

  • jdbcUrl

    Default: null

    The JDBC URL of the database from which Connections can and should be acquired. Should resolve via java.sql.DriverManager to an appropriate JDBC Driver (which you can ensure will be loaded and available by setting ```driverClass), or if you wish to specify which driver to use directly (and avoid DriverManager` resolution), you may specify driverClass in combination with forceUseNamedDriverClass. Unless you are supplying your own unpooled DataSource, a must always be provided and appropriate for the JDBC driver, however it is resolved.Does Not Support Per-User Overrides.

  • maxAdministrativeTaskTime

    Default: 0

    Seconds before c3p0’s thread pool will try to interrupt an apparently hung task. Rarely useful. Many of c3p0’s functions are not performed by client threads, but asynchronously by an internal thread pool. c3p0’s asynchrony enhances client performance directly, and minimizes the length of time that critical locks are held by ensuring that slow jdbc operations are performed in non-lock-holding threads. If, however, some of these tasks “hang”, that is they neither succeed nor fail with an Exception for a prolonged period of time, c3p0’s thread pool can become exhausted and administrative tasks backed up. If the tasks are simply slow, the best way to resolve the problem is to increase the number of threads, via numHelperThreads. But if tasks sometimes hang indefinitely, you can use this parameter to force a call to the task thread’s interrupt() method if a task exceeds a set time limit. [c3p0 will eventually recover from hung tasks anyway by signalling an “APPARENT DEADLOCK” (you’ll see it as a warning in the logs), replacing the thread pool task threads, and interrupt()ing the original threads. But letting the pool go into APPARENT DEADLOCK and then recover means that for some periods, c3p0’s performance will be impaired. So if you’re seeing these messages, increasing numHelperThreads and setting maxAdministrativeTaskTime might help. maxAdministrativeTaskTime should be large enough that any resonable attempt to acquire a Connection from the database, to test a Connection, or to destroy a Connection, would be expected to succeed or fail within the time set. Zero (the default) means tasks are never interrupted, which is the best and safest policy under most circumstances. If tasks are just slow, allocate more threads. If tasks are hanging forever, try to figure out why, and maybe setting maxAdministrativeTaskTime can help in the meantime.Does Not Support Per-User Overrides.

    在c3p0的线程池试图中断一个明显挂起的任务前几秒。很少有用。c3p0的许多函数不是由客户端线程执行的,而是由内部线程池异步执行的。C3p0的异步直接提高了客户端性能,通过确保在非锁持有线程中执行慢速JDBC操作,最小化了关键锁持有的时间长度。但是,如果其中一些任务“挂起”,即它们在很长一段时间内既不成功也不失败,并伴有异常,那么c3p0的线程池可能会耗尽,从而备份管理任务。如果任务很慢,解决这个问题的最好方法是通过numHelperThreads增加线程的数量。但是如果任务有时无限期地挂起,你可以使用这个参数来强制调用任务线程的’ interrupt() ‘方法,如果任务超过了设定的时间限制。[c3p0最终将通过发出“明显的死锁”信号(在日志中会看到这是一个警告)来从挂起的任务中恢复,替换线程池任务线程,并中断()原始线程。但是让池进入表观死锁,然后恢复意味着在一段时间内,c3p0的性能将受到损害。因此,如果你看到这些消息,增加numHelperThreads和设置’ maxAdministrativeTaskTime ‘可能会有所帮助。’ maxAdministrativeTaskTime '应该足够大,以至于任何合理的尝试从数据库获取连接,测试连接,或销毁连接,都将在设定的时间内预期成功或失败。0(默认值)意味着任务不会被中断,这在大多数情况下是最好和最安全的策略。如果任务很慢,那么分配更多线程。如果任务一直挂着,试着找出原因,在此期间设置“maxAdministrativeTaskTime”可能会有所帮助。不支持每用户重写。

  • maxConnectionAge

    Default: 0

    Seconds, effectively a time to live. A Connection older than maxConnectionAge will be destroyed and purged from the pool. This differs from maxIdleTime in that it refers to absolute age. Even a Connection which has not been much idle will be purged from the pool if it exceeds maxConnectionAge. Zero means no maximum absolute age is enforced.

    秒,有效地活了一段时间。大于“maxConnectionAge”的连接将被销毁并从池中清除。这与’ maxIdleTime ‘不同,因为它指的是绝对年龄。即使是一个没有太多空闲的连接,如果它超过了’ maxConnectionAge ',也会从池中清除。零意味着没有强制规定最大年龄。

  • maxIdleTime

    Default: 0

    Seconds a Connection can remain pooled but unused before being discarded. Zero means idle connections never expire. [See “Basic Pool Configuration”]

  • maxIdleTimeExcessConnections

    Default: 0

    Number of seconds that Connections in excess of minPoolSize should be permitted to remain idle in the pool before being culled. Intended for applications that wish to aggressively minimize the number of open Connections, shrinking the pool back towards minPoolSize if, following a spike, the load level diminishes and Connections acquired are no longer needed. If maxIdleTime is set, maxIdleTimeExcessConnections should be smaller if the parameter is to have any effect. Zero means no enforcement, excess Connections are not idled out.

    在被剔除之前,超过“minPoolSize”的连接应该被允许在池中保持空闲的秒数。适用于希望积极地最小化打开连接数量的应用程序,如果在峰值之后,负载水平降低,并且不再需要获得的连接,则将池缩小到minPoolSize。如果设置了’ maxIdleTime ‘,那么’ maxIdleTimeExcessConnections '应该更小,如果该参数要起作用的话。零意味着没有强制,多余的连接不会闲置。

  • maxPoolSize

    Default: 15

    Maximum number of Connections a pool will maintain at any given time. [See “Basic Pool Configuration”]

  • maxStatements

    Default: 0

    The size of c3p0’s global PreparedStatement cache. If both maxStatements and maxStatementsPerConnection are zero, statement caching will not be enabled. If maxStatements is zero but maxStatementsPerConnection is a non-zero value, statement caching will be enabled, but no global limit will be enforced, only the per-connection maximum. maxStatements controls the total number of Statements cached, for all Connections. If set, it should be a fairly large number, as each pooled Connection requires its own, distinct flock of cached statements. As a guide, consider how many distinct PreparedStatements are used frequently in your application, and multiply that number by maxPoolSize to arrive at an appropriate value. Though maxStatements is the JDBC standard parameter for controlling statement caching, users may find c3p0’s alternative maxStatementsPerConnection more intuitive to use. [See “Configuring Statement Pooling”]

  • maxStatementsPerConnection

    Default: 0

    The number of PreparedStatements c3p0 will cache for a single pooled Connection. If both maxStatements and maxStatementsPerConnection are zero, statement caching will not be enabled. If maxStatementsPerConnection is zero but maxStatements is a non-zero value, statement caching will be enabled, and a global limit enforced, but otherwise no limit will be set on the number of cached statements for a single Connection. If set, maxStatementsPerConnection should be set to about the number distinct PreparedStatements that are used frequently in your application, plus two or three extra so infrequently statements don’t force the more common cached statements to be culled. Though maxStatements is the JDBC standard parameter for controlling statement caching, users may find maxStatementsPerConnection more intuitive to use. [See “Configuring Statement Pooling”]

    preparedstatement c3p0的数量将为单个池连接缓存。如果’ maxStatements ‘和’ maxStatementsPerConnection '都为零,语句缓存将不会被启用。如果“maxStatementsPerConnection”为零,但“maxStatements”为非零值,则将启用语句缓存,并强制执行全局限制,否则不会对单个连接的缓存语句数量设置限制。如果设置了maxStatementsPerConnection,应该将其设置为在应用程序中频繁使用的不同preparedstatement的数量,再加上两到三个额外的,这样不频繁的语句就不会强制选择更常见的缓存语句。虽然“maxStatements”是用于控制语句缓存的JDBC标准参数,但用户可能会发现“maxStatementsPerConnection”使用起来更直观。

  • minPoolSize

    Default: 3

    Minimum number of Connections a pool will maintain at any given time. [See “Basic Pool Configuration”]

  • numHelperThreads

    Default: 3

    c3p0 is very asynchronous. Slow JDBC operations are generally performed by helper threads that don’t hold contended locks. Spreading these operations over multiple threads can significantly improve performance by allowing multiple operations to be performed simultaneously.

  • overrideDefaultUser

    Default: null

    Forces the username that should by PooledDataSources when a user calls the default getConnection() method. This is primarily useful when applications are pooling Connections from a non-c3p0 unpooled DataSource. Applications that use ComboPooledDataSource, or that wrap any c3p0-implemented unpooled DataSource can use the simple user property.Does Not Support Per-User Overrides.

  • overrideDefaultPassword

    Default: null

    Forces the password that should by PooledDataSources when a user calls the default getConnection() method. This is primarily useful when applications are pooling Connections from a non-c3p0 unpooled DataSource. Applications that use ComboPooledDataSource, or that wrap any c3p0-implemented unpooled DataSource can use the simple password property.Does Not Support Per-User Overrides.

  • password

    Default: null

    For applications using ComboPooledDataSource or any c3p0-implemented unpooled DataSources — DriverManagerDataSource or the DataSource returned by DataSources.unpooledDataSource( ... ) — defines the password that will be used for the DataSource’s default getConnection() method. (See also user.)Does Not Support Per-User Overrides.

  • preferredTestQuery

    Default: null

    Defines the query that will be executed for all connection tests, if the default ConnectionTester (or some other implementation of QueryConnectionTester, or better yet FullQueryConnectionTester) is being used. Defining a preferredTestQuery that will execute quickly in your database may dramatically speed up Connection tests. (If no preferredTestQuery is set, the default ConnectionTester executes a getTables() call on the Connection’s DatabaseMetaData. Depending on your database, this may execute more slowly than a “normal” database query.) NOTE: The table against which your preferredTestQuery will be run must exist in the database schema *prior* to your initialization of your DataSource. If your application defines its own schema, try automaticTestTable instead. [See “Configuring Connection Testing”]

  • privilegeSpawnedThreads

    Default: false

    If true, c3p0-spawned Threads will have the java.security.AccessControlContext associated with c3p0 library classes. By default, c3p0-spawned Threads (helper threads, java.util.Timer threads) inherit their AccessControlContext from the client Thread that provokes initialization of the pool. This can sometimes be a problem, especially in application servers that support hot redeployment of client apps. If c3p0’s Threads hold a reference to an AccessControlContext from the first client that hits them, it may be impossible to garbage collect a ClassLoader associated with that client when it is undeployed in a running VM. Also, it is possible client Threads might lack sufficient permission to perform operations that c3p0 requires. Setting this to true can resolve these issues. [See “Configuring To Avoid Memory Leaks On Hot Redeploy Of Client”]Does Not Support Per-User Overrides.

  • propertyCycle

    Default: 0

    Maximum time in seconds before user configuration constraints are enforced. Determines how frequently maxConnectionAge, maxIdleTime, maxIdleTimeExcessConnections, unreturnedConnectionTimeout are enforced. c3p0 periodically checks the age of Connections to see whether they’ve timed out. This parameter determines the period. Zero means automatic: A suitable period will be determined by c3p0. [You can call getEffectivePropertyCycle...() methods on a c3p0 PooledDataSource to find the period automatically chosen.]

    用户配置约束生效的最大时间(秒)。确定强制执行’ maxConnectionAge ', ’ maxIdleTime ', ’ maxIdleTimeExcessConnections ', ’ unreturnedConnectionTimeout '的频率。c3p0定期检查连接的年龄,看它们是否超时。该参数决定周期。0表示自动:一个合适的周期将由c3p0确定。

  • statementCacheNumDeferredCloseThreads

    Default: 0

    If set to a value greater than 0, the statement cache will track when Connections are in use, and only destroy Statements when their parent Connections are not otherwise in use. Although closing of a Statement while the parent Connection is in use is formally within spec, some databases and/or JDBC drivers, most notably Oracle, do not handle the case well and freeze, leading to deadlocks. Setting this parameter to a positive value should eliminate the issue. This parameter should only be set if you observe that attempts by c3p0 to close() cached statements freeze (usually you’ll see APPARENT DEADLOCKS in your logs). If set, this parameter should almost always be set to 1. Basically, if you need more than one Thread dedicated solely to destroying cached Statements, you should set maxStatements and/or maxStatementsPerConnection so that you don’t churn through Statements so quickly. [See “Configuring Statement Pooling”]Does Not Support Per-User Overrides.

  • testConnectionOnCheckin

    Default: false

    If true, an operation will be performed asynchronously at every connection checkin to verify that the connection is valid. Use in combination with idleConnectionTestPeriod for quite reliable, always asynchronous Connection testing. Also, setting an automaticTestTable or preferredTestQuery will usually speed up all connection tests. [See “Configuring Connection Testing”]

  • testConnectionOnCheckout

    Default: false

    If true, an operation will be performed at every connection checkout to verify that the connection is valid. *Be sure to set an efficient* preferredTestQuery *or* automaticTestTable *if you set this to* true. *Performing the (expensive) default Connection test on every client checkout will harm client performance.* Testing Connections in checkout is the simplest and most reliable form of Connection testing, but for better performance, consider verifying connections periodically using idleConnectionTestPeriod. [See “Configuring Connection Testing”]

  • unreturnedConnectionTimeout

    Default: 0

    Seconds. If set, if an application checks out but then fails to check-in [i.e. close()] a Connection within the specified period of time, the pool will unceremoniously destroy() the Connection. This permits applications with occasional Connection leaks to survive, rather than eventually exhausting the Connection pool. And that’s a shame. Zero means no timeout, applications are expected to close() their own Connections. Obviously, if a non-zero value is set, it should be to a value longer than any Connection should reasonably be checked-out. Otherwise, the pool will occasionally kill Connections in active use, which is bad. *This is basically a bad idea, but it’s a commonly requested feature. Fix your $%!@% applications so they don’t leak Connections! Use this temporarily in combination with debugUnreturnedConnectionStackTraces to figure out where Connections are being checked-out that don’t make it back into the pool!* [See “Configuring to Debug and Workaround Broken Client Applications”]

  • user

    Default: null

    For applications using ComboPooledDataSource or any c3p0-implemented unpooled DataSources — DriverManagerDataSource or the DataSource returned by DataSources.unpooledDataSource() — defines the username that will be used for the DataSource’s default getConnection() method. (See also password.)Does Not Support Per-User Overrides.

十二、网络闪断c3p0线程堵塞解决方法

场景:c3p0数据库连接耗尽,新的工作线程获取连接时进入堵塞状态,此时网络关闭。获取连接成功的工作线程由于断网没有接收到数据库的回应会一直堵塞等待数据返回。获取连接而堵塞的工作线程也会一直堵塞下去。

解决方法:通过设置驱动底层socket的soTimeout可以使socket通过抛出timeout异常,解除线程堵塞状态,提前返回。

通过测试,估算出交易中sql最大运行时间,推荐设置为

Sql最大运行时间< c3p0 MaxIdleTime < soTimeout

soTimeout在不同数据库中设置

数据库 设置方法
mysql url设置socketTimeout,单位毫秒比如设置为30秒在url后添加参数&socketTimeout=30000
oracle 虚拟机设置参数,单位毫秒比如设置为30秒在启动程序时设置-Doracle.jdbc.ReadTimeout=30000
db2 单位秒设置loginTimeout,QueryTimeout,blockingReadConnectionTimeout(待验证)

C3P0数据库连接池的解析相关推荐

  1. Java数据库开发与应用之MySQL数据库、JDBC操作数据库、C3P0数据库连接池,Java反射等

    MySQL数据库,JDBC接口,MyBatis框架等,掌握的数据的存放和管理. Java数据库开发基础,介绍MySQL数据库.JDBC操作数据库.C3P0数据库连接池,Java反射等内容,进行油画商城 ...

  2. c3p0 数据库连接池

    C3P0连接池 c3p0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展.c3p0一般是与Hibernate,Spring等框架一块使用的,当然也可以 ...

  3. [原创]java WEB学习笔记80:Hibernate学习之路--- hibernate配置文件:JDBC 连接属性,C3P0 数据库连接池属性等...

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  4. 数据库连接池种类、C3P0数据库连接池、德鲁伊数据库连接池

    数据库连接池种类 1.JDBC的数据库连接池使用javax.sql.DataSource来表示,DataSource只是一个接口,该接口通常由第三方提供实现 2.C3P0数据库连接池,速度相对较慢,稳 ...

  5. 数据库连接池及C3P0数据库连接池技术

    数据库连接池(重要) 注意数据库连接池只是简化获得数据库连接对象和关流的部门 1.数据库连接池: 1.概念: 其实就是一个容器(在Java中就是集合),存在数据库连接的容器,当系统初始化好后,容器被创 ...

  6. 数据库连接池 DBCP和c3p0数据库连接池

    一.数据库连接池 1. 什么是连接池 传统的开发模式下,Servlet处理用户的请求,找Dao查询数据,dao会创建与数据库之间的连接,完成数据查询后会关闭数据库的链接. 这样的方式会导致用户每次请求 ...

  7. 【JDBC】使用c3p0数据库连接池的各种报错警告

    使用c3p0数据库连接池的各种报错警告 使用c3p0数据库连接池的时候,先导入了三个jar包在lib 文件夹中, c3p0-0.9.5.2.jar mchange-commons-java-0.2.3 ...

  8. C3P0数据库连接池的配置

    在pom.xml文件中导入jar包 <dependency><groupId>com.mchange</groupId><artifactId>c3p0 ...

  9. C3P0数据库连接池源代码

    步骤如下: 导入c3p0-0.9.1.2.jar 1. 创建 c3p0-config.xml 文件,  2. 创建 ComboPooledDataSource 实例:  DataSource data ...

最新文章

  1. 宏基因组理论教程2扩增子分析
  2. codelite14中文语言包_Windows下CodeLite完美支持中文的正确设置方法
  3. SAP Spartacus B2B Unit page convertListItem方法的工作原理
  4. figma下载_迁移至Figma
  5. c php乱码,php分割GBK中文乱码的解决方法
  6. 初使用 ReportViewer 控件时遇到的一点小麻烦
  7. 表面上承认错误_做一个可以承认错误的领导者
  8. 广告传媒实际税负怎么计算_传媒宣传业增值税税负多少
  9. qt的opengl开发(qopenglwidget)(初始化,画线,平移,局部缩放)2d开发
  10. abaqus 帮助文档
  11. 2010-2019年款北汽原厂维修手册电路图线路图资料下载
  12. 高端玩家的运营与维护
  13. 外贸单证管理可高效简化外贸进出口制单流程
  14. oracle中的than,range分区values less than,代表的是小于等于还是小于啊。
  15. 计算机教育影片观后感,2020青少年法治教育片沉重的爱观后感大全
  16. Arduino基础入门二之呼吸灯
  17. Java 常用的基本关键字和常用单词
  18. php国际象棋棋盘,php趣味编程 - php输出国际象棋棋盘
  19. uni-app 24h无人共享洗车-自助洗车小程序-带商城开源了~
  20. 快速学习-Saturn FAQ

热门文章

  1. 4月10号软件资讯更新合集.....
  2. idea 调式快捷键_eclipse/idea调试快捷键
  3. ICP(迭代最近点)算法推导详解
  4. 指南针,城市生活新向导
  5. facebook数据爬取
  6. 计算机编程语言排序,计算机入门必备算法——选择排序法
  7. 2016 西普杯丶天津CTF预选赛(3/6)
  8. 写给即将入职的你-软件工程之需求开发流程 1
  9. IDEA常用快捷键及修改快捷键
  10. WEB前端知识大整合之Jquery表单隔行换色