[英]com.mysql.cj.jdbc.exceptions.CommunicationsException: The last packet successfully received from the server was XXXXXXXXXXXX milliseconds ago
I have a spring boot application that does not use connection pool and we didn't want to open a DB connection at every request 我有一个不使用连接池的Spring Boot应用程序,我们不想在每个请求时都打开数据库连接
So, here is what we have in a class called MySQLService
which has methods with DB queries: 因此,这就是我们称为MySQLService
的类中的内容,该类具有用于DB查询的方法:
@Autowired
@Qualifier("mysqlDB")
private Connection connection;
This connection
object is always used in all of the methods with queries. 此connection
对象始终在所有带有查询的方法中使用。
In MySQLConnection class, 在MySQLConnection类中,
@Bean(name = "mysqlDB")
public Connection getConnection() {
Connection connection = null;
try {
Class.forName(mysqlDriver);
LOGGER.debug("get mysql connection...");
connection = DriverManager
.getConnection(jdbcUrl,
user, password);
} catch (Exception exception) {
LOGGER.error("ERROR :: {}", exception);
}
return connection;
}
}
So, we are never really closing the connection, it is being managed by spring context but since we are not using JDBCTemplates, it does not get closed. 因此,我们永远不会真正关闭连接,它是由spring上下文管理的,但是由于我们没有使用JDBCTemplates,因此不会关闭它。 We have autoreconnect
set to true
in connection string. 我们在连接字符串中将autoreconnect
设置为true
。
In a day or two, we get the exception: 在一两天内,我们会得到一个例外:
com.mysql.cj.jdbc.exceptions.CommunicationsException: The last packet successfully received from the server was 61,183,452 milliseconds ago.
I understand it is because SQL Server has connection lifetime set so it expires the connection but what is a way to handle this without using a connection pool 我了解这是因为SQL Server设置了连接生存期,因此它会使连接过期,但是在不使用连接池的情况下如何处理此问题?
Schedule a ping to the MySQL Server every 6 hours or so, executing this query: select 1 from dual
. 每6个小时左右对MySQL服务器进行一次ping调度,执行此查询: select 1 from dual
。 For that, you need to enable scheduling: 为此,您需要启用调度:
@Configuration
@EnableScheduling
public class SpringConfig {
//...
}
then: 然后:
@Scheduled(cron = "0 */6 * * *")
public void schedulePingMySQL() {
// execute `select 1 from dual`
}
Anyway, using a connection pool is the recommended way. 无论如何,建议使用连接池。 This case the code may look like: 这种情况下的代码可能如下所示:
@Autowired
private DataSource dataSource;
public void save (Dto dto) {
Connection con = dataSource.getConnection();
// finally, close the connection
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.