search
HomeDatabaseMysql Tutorialmysql 8小connection悬空问题及解决办法

今早起来无意间登陆了一下昨晚发布的项目,出乎意料的报了一个错误。不过学习的机会又来了,问题如下。 上网大致搜了一下,发现这是一个普遍存在的问题,还有个很霸气的名字叫做mysql 8小connection悬空问题。其实是由于Mysql连接超时所导致的。具体原因是My

今早起来无意间登陆了一下昨晚发布的项目,出乎意料的报了一个错误。不过学习的机会又来了,问题如下。mysql 8小connection悬空问题及解决办法

上网大致搜了一下,发现这是一个普遍存在的问题,还有个很霸气的名字叫做mysql 8小connection悬空问题。其实是由于Mysql连接超时所导致的。具体原因是Mysql服务器默认的“wait_timeout”是8小时【也就是默认的值默认是28800秒】,也就是说一个connection空闲超过8个小时,Mysql将自动断开该connection,通俗的讲就是一个连接在8小时内没有活动,就会自动断开该连接。wait timeout的值可以设定,但最多只能是2147483,不能再大了。也就是约24.85天

          解决的办法那么两三种,最为有效地办法就是建立连接池,会定期维护连接,并处理自动关闭的这种情况。其他几种方法不理想就不做解释和记录了。

在我的项目中采用了hibernate,然而hibernate自带的连接池实在太渣(听说,没有考证,但出现了这个问题可以从一方面看出不给力)。所以只能采用主流的连接池,有这么几种。

1. DBCP.

Apche的DBCP在Hibernate2中受支持,但在Hibernate3中已经不再推荐使用,官方的解释是这个连接池存在缺陷。如果你因为某种原因需要在Hibernate3中使用DBCP,建议采用JNDI方式。

2.C3P0.

Hibernate2和Hibernate3的命名空间有所变化。例如,配置C3P0时的provider_class有Hibernate2环境下使用net.sf.hibernate.connection.C3P0ConnectionProvider,在Hibernate3环境下使用org.hibernate.connection.C3P0ConnectionProvider。

3.Proxool

至于三者的比较,网上有很多大家可以去查找,我发现一个比较有趣的小实验,可以自己编码来测试性能,大家可以试试。

有趣的实验还添加了与druid的比较(http://286.iteye.com/blog/1920417)

在我的项目一种我选择了c3p0,现将配置过程罗列如下:

hibernate.cfg.xml


<hibernate-configuration>

	<session-factory>
		
	<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> 
        <!--连接池的最小连接数-->    
        <property name="c3p0.min_size">5</property>  
        <!--最大连接数-->    
        <property name="c3p0.max_size">30</property>  
        <!--连接超时时间-->  
        <property name="c3p0.timeout">1800</property>  
        <!--statemnets缓存大小-->    
        <property name="c3p0.max_statements">100</property>  
        <!--每隔多少秒检测连接是否可正常使用  -->    
        <property name="c3p0.idle_test_period">121</property>  
        <!--当池中的连接耗尽的时候,一次性增加的连接数量,默认为3-->    
        <property name="c3p0.acquire_increment">3</property>  
        <property name="c3p0.validate">true</property>
		<!-- 连接池每隔60秒自动检测数据库连接情况,如果断开则自动重连 -->
		<property name="idleConnectionTestPeriod">60</property>
		<property name="testConnectionOnCheckout">true</property>
		
		
		<property name="dialect">
			org.hibernate.dialect.MySQLDialect
		</property>
		<property name="connection.url">
			jdbc:mysql://xxxx:3306/xxx?useUnicode=true&characterEncoding=UTF8
		</property>
		<property name="connection.username">username</property>
		<property name="connection.password">password</property>
		<property name="connection.driver_class">
			com.mysql.jdbc.Driver
		</property>
		
		<mapping resource="com/demontf/bean/Project.hbm.xml"></mapping>
		<mapping resource="com/demontf/bean/User.hbm.xml"></mapping>

	</session-factory>
	
	

</hibernate-configuration>

一个不错的hibernate配置c3p0的教程:http://www.cnblogs.com/best/archive/2013/05/09/3069839.html

网上很多一部分教程是说下面这个语句一定要加,其实在这里我倒没出什么错误,主要是在问题出在引包中。


<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> 

开始导入的是c3p0-0.9.2.1.jar ,但总是出现问题,Could not initialize class com.dao.HibernateSessionFactory。最终,导入以下两个jar包解决该问题c3p0配置成功

c3p0-0.9.1.jar和hibernate-c3p0-4.1.11.Final.jar(我已经将资源上传)

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
MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

MySQL: String Data Types and ENUMs?MySQL: String Data Types and ENUMs?May 13, 2025 am 12:05 AM

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

MySQL BLOB: how to optimize BLOBs requestsMySQL BLOB: how to optimize BLOBs requestsMay 13, 2025 am 12:03 AM

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.