`
thingkau
  • 浏览: 72467 次
  • 性别: Icon_minigender_1
  • 来自: 泉州
社区版块
存档分类
最新评论

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&amp;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 -->
分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

Global site tag (gtag.js) - Google Analytics