search
HomeDatabaseMysql Tutorialc3p0数据源的使用初步及Mysql8小时有关问题解决

c3p0数据源的使用初步及Mysql8小时问题解决 c3p0号称是java界最好的数据池。 c3p0的配置方式分为三种,分别是 1.setters一个个地设置各个配置项 2.类路径下提供一个c3p0.properties文件 3.类路径下提供一个c3p0-config.xml文件 我们主要说下c3p0-config.xml配

c3p0数据源的使用初步及Mysql8小时问题解决

c3p0号称是java界最好的数据池。


c3p0的配置方式分为三种,分别是

1.setters一个个地设置各个配置项

2.类路径下提供一个c3p0.properties文件

3.类路径下提供一个c3p0-config.xml文件

我们主要说下c3p0-config.xml配置:


//默认池配置

 

root

java

com.mysql.jdbc.Driver

jdbc:mysql://localhost:3306/jdbc


   10

   30

   100

   10

 

 //命名池配置

 

root

java

com.mysql.jdbc.Driver

jdbc:mysql://localhost:3306/jdbc

   10

   30

   100

   10

 


可见c3p0可以配置在一个应用中使用多个池。换言之可以使用多个数据库。

使用:

//使用默认池:

private static ComboPooledDataSource ds = new ComboPooledDataSource();

//使用命名池

private static ComboPooledDataSource ds = new ComboPooledDataSource("myApp");

基本配置项的介绍:


1.基本配置

acquireIncrement

default : 3

连接池在无空闲连接可用时一次性创建的新数据库连接数

initialPoolSize

default : 3

连接池初始化时创建的连接数

maxPoolSize

default : 15

连接池中拥有的最大连接数,如果获得新连接时会使连接总数超过这个值则不会再获取新连接,而是等待

其他连接释放,所以这个值有可能会设计地很大

maxIdleTime

default : 0 单位 s

连接的最大空闲时间,如果超过这个时间,某个数据库连接还没有被使用,则会断开掉这个连接

如果为0,则永远不会断开连接

minPoolSize

default : 3

连接池保持的最小连接数,后面的maxIdleTimeExcessConnections跟这个配合使用来减轻连接池的负载


2.管理连接池的大小和连接的生存时间

maxConnectionAge

default : 0 单位 s

配置连接的生存时间,超过这个时间的连接将由连接池自动断开丢弃掉。当然正在使用的连接不会马上断开,而是等待

它close再断开。配置为0的时候则不会对连接的生存时间进行限制。

maxIdleTimeExcessConnections

default : 0 单位 s

这个配置主要是为了减轻连接池的负载,比如连接池中连接数因为某次数据访问高峰导致创建了很多数据连接

但是后面的时间段需要的数据库连接数很少,则此时连接池完全没有必要维护那么多的连接,所以有必要将

断开丢弃掉一些连接来减轻负载,必须小于maxIdleTime。配置不为0,则会将连接池中的连接数量保持到minPoolSize。

为0则不处理。

3.配置连接测试:因为连接池中的数据库连接很有可能是维持数小时的连接,很有可能因为数据库服务器的问题,网络问题等导致实际连接已经无效,但是连接池里面的连接还是有效的,如果此时获得连接肯定会发生异常,所以有必要通过测试连接来确认连接的有效性。

下面的前三项用来配置如何对连接进行测试,后三项配置对连接进行测试的时机。

automaticTestTable

default : null

用来配置测试连接的一种方式。配置一个表名,连接池根据这个表名创建一个空表,

并且用自己的测试sql语句在这个空表上测试数据库连接

这个表只能由c3p0来使用,用户不能操作,同时用户配置的preferredTestQuery 将会被忽略。

preferredTestQuery

default : null

用来配置测试连接的另一种方式。与上面的automaticTestTable二者只能选一。

如果要用它测试连接,千万不要设为null,否则测试过程会很耗时,同时要保证sql语句中的表在数据库中一定存在。

connectionTesterClassName

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

连接池用来支持automaticTestTable和preferredTestQuery测试的类,必须是全类名,就像默认的那样,

可以通过实现UnifiedConnectionTester接口或者继承AbstractConnectionTester来定制自己的测试方法

idleConnectionTestPeriod

default : 0

用来配置测试空闲连接的间隔时间。测试方式还是上面的两种之一,可以用来解决MySQL8小时断开连接的问题。因为它

保证连接池会每隔一定时间对空闲连接进行一次测试,从而保证有效的空闲连接能每隔一定时间访问一次数据库,将于MySQL

8小时无会话的状态打破。为0则不测试。

testConnectionOnCheckin

default : false

如果为true,则在close的时候测试连接的有效性。为了提高测试性能,可以与idleConnectionTestPeriod搭配使用,

配置preferredTestQuery或automaticTestTable也可以加快测试速度。

testConnectionOnCheckout

default : false

性能消耗大。如果为true,在每次getConnection的时候都会测试,为了提高性能,

可以与idleConnectionTestPeriod搭配使用,

配置preferredTestQuery或automaticTestTable也可以加快测试速度。

4.配置PreparedStatement缓存

maxStatements

default : 0

连接池为数据源缓存的PreparedStatement的总数。由于PreparedStatement属于单个Connection,所以

这个数量应该根据应用中平均连接数乘以每个连接的平均PreparedStatement来计算。为0的时候不缓存,

同时maxStatementsPerConnection的配置无效。

maxStatementsPerConnection

default : 0

连接池为数据源单个Connection缓存的PreparedStatement数,这个配置比maxStatements更有意义,因为

它缓存的服务对象是单个数据连接,如果设置的好,肯定是可以提高性能的。为0的时候不缓存。

注意当数据池不再使用时需要调用close()方法手动关闭它配置举例:

我的c3p0配置实例:

<c3p0-config>
<!--解决Mysql 8小时问题 -->
<default-config>
<property name="automaticTestTable">C3P0Test</property>
<property name="idleConnectionTestPeriod">60</property>
<!--设置为2个小时 -->
<property name="maxIdleTime">60</property> 
<!--获取连接时测试是否有效 ,消耗较大,不建议使用-->
<!-- <property name="testConnectionCheckin">true</property> -->
<!--  -->
<property name="initialPoolSize">10</property>
<property name="maxPoolSize">100</property> 
<property name="minPoolSize">10</property> 
<property name="maxStatements">100</property>

<!--获取连接超时毫秒为单位--->
<property name="checkoutTimeout">30000</property>
</default-config>
</c3p0-config>




解决MYSQL 8小时问题

Mysql服务器默认的“wait_timeout”是8小时,也就是说一个connection空闲超过8个小时,Mysql将自动断开该 connection。这就是问题的所在,在C3P0 pools中的connections如果空闲超过8小时,Mysql将其断开,而C3P0并不知道该connection已经失效,如果这时有 Client请求connection,C3P0将该失效的Connection提供给Client,将会造成上面的异常。

解决的方法有3种:

   增加wait_timeout的时间。

   减少Connection pools中connection的lifetime。

   测试Connection pools中connection的有效性。

C3P0增加以下配置信息:

   //自动测试的table名称

   automaticTestTable=C3P0TestTable

   //set to something much less than wait_timeout, prevents connections from going stale。每个小时测试一次

   idleConnectionTestPeriod = 3600

   //set to something slightly less than wait_timeout, preventing 'stale' connections from being handed out最大空闲时间为2个小时

   maxIdleTime = 7200

//获取connnection时测试是否有效

testConnectionOnCheckin = true




整体说明:

3

30

1000

false

Test

false

100

null

false

60

3

60

15

100

3

root

password

select id from test where id=1

300

false

true





补充一点,与c3p0配置无关,但是对于tomcat中配置DBCP很重要。

对于tomcat中的DBCP,也需要解决Mysql 8小时问题,所以需要这样:

  //set to 'SELECT 1'

  validationQuery = "SELECT 1"

  //set to 'true'

  testWhileIdle = "true"

  //some positive integer

  timeBetweenEvictionRunsMillis = 3600000

  //set to something smaller than 'wait_timeout'

  minEvictableIdleTimeMillis = 18000000

  //if you don't mind a hit for every getConnection(), set to "true"

  testOnBorrow = "true"

参考:http://my.oschina.net/lyzg/blog/55133

http://www.blogjava.net/Alpha/archive/2009/03/29/262789.html


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools