SpringBoot解决mysql 连接8小时问题

SpringBoot解决mysql 连接8小时问题

问题: 服务连接mysql数据库,8小时没有数据库的操作时候,数据库会主动断开连接释放资源

解决办法总共4种方法

  1. MySQL 5版本之前可以通过在URL后面加入autoReconnect=true

  2. application.properties文件中加入:

    spring.datasource.test-on-borrow=true #(即在获取Connection对象时检测其可用性),不过这样会影响性能,但是这个配置是最有效的。
    spring.datasource.test-while-idle=true
    spring.datasource.time-between-eviction-runs-millis= 3600000
    
  3. ** 数据库配置调整:**

    如果你有权限访问 MySQL 服务器的配置,你也可以调整 MySQL 的连接超时时间。修改 wait_timeoutinteractive_timeout 参数,将它们设置为一个更大的值,以延长连接的存活时间。

    请注意,修改 MySQL 服务器的配置可能需要谨慎考虑,因为这会影响到所有连接

    my.ini 文件中修改此参数

    [mysqld]
    wait_timeout=31536000
    interactive_timeout=31536000
    
  4. 定时任务发送查询:

    如果你没有使用连接池,你可以创建一个定时任务,在一定时间间隔内发送一个查询来保持连接活跃。这可以使用 Spring 的 @Scheduled 注解来实现

    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    @Component
    public class KeepAliveTask {
          
          
        private final JdbcTemplate jdbcTemplate;
    
        public KeepAliveTask(JdbcTemplate jdbcTemplate) {
          
          
            this.jdbcTemplate = jdbcTemplate;
        }
    
        @Scheduled(fixedRate = 300000) // 5 minutes
        public void keepConnectionAlive() {
          
          
            jdbcTemplate.queryForObject("SELECT 1", Integer.class);
        }
    }
    
    

猜你喜欢

转载自blog.csdn.net/caidingnu/article/details/132411301