我有一个不使用连接池的春季启动应用程序
所以,这是我们在一个名为MySQLService
的类中拥有的,该类别具有带有数据库查询的方法:
@Autowired
@Qualifier("mysqlDB")
private Connection connection;
此connection
对象始终在所有具有查询的方法中使用。
在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;
}
}
因此,我们永远不会真正关闭连接,它是由春季上下文管理的,但是由于我们没有使用JDBCTEMPLATES,因此它不会被关闭。我们在连接字符串中将autoreconnect
设置为true
。
在一两天内,我们得到例外:
com.mysql.cj.jdbc.exceptions.CommunicationsException: The last packet successfully received from the server was 61,183,452 milliseconds ago.
我知道这是因为SQL Server具有连接寿命集,因此它会到期,但是在不使用连接池
每6小时左右将ping安排到MySQL Server,执行此查询:select 1 from dual
。为此,您需要启用调度:
@Configuration
@EnableScheduling
public class SpringConfig {
//...
}
然后:
@Scheduled(cron = "0 */6 * * *")
public void schedulePingMySQL() {
// execute `select 1 from dual`
}
无论如何,使用连接池是建议的。这种情况可能看起来像:
@Autowired
private DataSource dataSource;
public void save (Dto dto) {
Connection con = dataSource.getConnection();
// finally, close the connection
}