JAVA MYSQL 8小时后自动断开连接

如果连接闲置8小时 (8小时内没有进行数据库操作), mysql就会自动断开连接, 得刷新应用才行.  

    不用hibernate的话, connection url加参数: autoReconnect=true  
    用hibernate的话, 加如下属性:  
         <property name="connection.autoReconnect">true</property> 
        <property name="connection.autoReconnectForPools">true</property> 
        <property name="connection.is-connection-validation-required">true</property>
 
    要是还用c3p0连接池:  
         <property name="hibernate.c3p0.acquire_increment">1</property> 
        <property name="hibernate.c3p0.idle_test_period">0</property> 
        <property name="hibernate.c3p0.timeout">0</property> 
        <property name="hibernate.c3p0.validate">true</property>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MySQL连接池可以使用一些开源的库来实现,如Druid、HikariCP、C3P0等。这些库都提供了连接池的常见功能,包括自动重连。 以Druid为例,Druid提供了配置参数`maxEvictableIdleTimeMillis`,该参数用于设置连接在连接池中闲置的最大时间,超过该时间的连接将被关闭。同时,Druid提供了配置参数`timeBetweenEvictionRunsMillis`,该参数用于设置定期检查连接是否已经过期的时间间隔。当定期检查发现连接已经过期时,Druid自动重连。 下面是一个使用Druid连接池的例子: ```java import com.alibaba.druid.pool.DruidDataSource; import java.sql.Connection; import java.sql.SQLException; public class ConnectionManager { private static DruidDataSource dataSource; static { dataSource = new DruidDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost/test"); dataSource.setUsername("root"); dataSource.setPassword("root"); dataSource.setInitialSize(5); dataSource.setMaxActive(10); dataSource.setMaxWait(60000); dataSource.setMinIdle(3); dataSource.setMaxIdle(8); dataSource.setTestOnBorrow(true); dataSource.setValidationQuery("SELECT 1"); dataSource.setRemoveAbandoned(true); dataSource.setRemoveAbandonedTimeout(1800); dataSource.setLogAbandoned(true); dataSource.setFilters("stat,wall"); dataSource.setMaxEvictableIdleTimeMillis(30000); dataSource.setTimeBetweenEvictionRunsMillis(60000); } public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } } ``` 在上面的例子中,我们设置了`maxEvictableIdleTimeMillis`为30秒,即连接在连接池中闲置30秒以上的将被关闭。同时,我们设置了`timeBetweenEvictionRunsMillis`为60秒,即每隔60秒定期检查连接是否已经过期。当Druid检查到连接已经过期时,将自动重连。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值