JAVA中对MySQL的链接池配置

MySQL 中默认在8小时后关闭闲置链接。为了测试,修改my.ini文件在最后添上以下内容:

#auto close idle connection after 10 seconds.
wait_timeout=10


假设使用DBCP做链接池,做如下配置:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/dbname?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>

<property name="initialSize" value="1"/>
<property name="maxActive" value="20"/>
<property name="maxWait" value="10"/>
<property name="maxIdle" value="2"/>
<property name="minIdle" value="1"/>
<property name="testWhileIdle" value="true"/>
<property name="minEvictableIdleTimeMillis" value="10000"/>
<property name="timeBetweenEvictionRunsMillis" value="10000"/>
</bean>

这样保证了被MySQL 关闭的连接对应于 链接池中的连接对象及时被清理,可以避免了MySQLIO异常,The last packet successfully received from the server was 46,958,922 milliseconds ago. The last packet sent successfully to the server was 46,958,922 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.

配置解释:
timeBetweenEvictionRunsMillis=10000启动一个子线程每隔10秒检测闲置连接,连接对象个数,并对无效连接进行Evict清理操作。
minEvictableIdleTimeMillis=10000连接对象闲置10秒后允许被Evict清理。
testWhileIdle=true是否检查闲置连接对象。

hibernate里配置C3P0链接池属性:

<!-- C3P0 Connection Pool -->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.timeout">100</property><!-- 连接对象允许的闲置时间(以秒为单位) -->
<property name="hibernate.c3p0.idle_test_period">100</property><!-- 每隔100秒检测连接是否可正常使用 -->
<property name="hibernate.c3p0.acquire_increment">3</property><!-- 当池中的连接耗尽的时候,一次性增加的连接数量,默认为3 -->
<property name="hibernate.c3p0.max_statements">100</property><!-- statemnets缓存大小 -->
<!-- hibernate.c3p0.validate :检查连接,推荐使用hibernate.c3p0.idle_test_period_代替,默认值为false -->
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值