SpringBoot解决mysql 连接8小时问题

SpringBoot解决mysql 连接8小时问题

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

解决办法总共4种方法

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

application.properties文件中加入:

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

** 数据库配置调整:**

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

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

my.ini 文件中修改此参数

ini 复制代码
[mysqld]
wait_timeout=31536000
interactive_timeout=31536000

定时任务发送查询:

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

java 复制代码
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);
    }
}
相关推荐
云之兕9 分钟前
Spring Boot 中多线程的基础使用
java·前端·spring boot
他҈姓҈林҈9 分钟前
Spring Boot 升级指南(2.x → 3.x)
spring boot
小白教程1 小时前
解读和分析mysql性能数据时,如何确定性能瓶颈的具体位置?
数据库·mysql·mysql教程·mysql优化教程
LaughingZhu1 小时前
PH热榜 | 2025-04-26
前端·数据库·人工智能·mysql·开源
why1518 小时前
腾讯(QQ浏览器)后端开发
开发语言·后端·golang
老友@8 小时前
小集合 VS 大集合:MySQL 去重计数性能优化
数据库·mysql·性能优化
浪裡遊8 小时前
跨域问题(Cross-Origin Problem)
linux·前端·vue.js·后端·https·sprint
声声codeGrandMaster8 小时前
django之优化分页功能(利用参数共存及封装来实现)
数据库·后端·python·django
呼Lu噜9 小时前
WPF-遵循MVVM框架创建图表的显示【保姆级】
前端·后端·wpf
bing_1589 小时前
为什么选择 Spring Boot? 它是如何简化单个微服务的创建、配置和部署的?
spring boot·后端·微服务