From 8b4c9dfff17dfcefdeeff7c615dfa9709af93a00 Mon Sep 17 00:00:00 2001 From: Spark <2666652@gmail.com> Date: Sat, 12 Oct 2024 00:51:53 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=E8=BF=9E=E6=8E=A5=E9=A2=84=E7=83=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../config/DatabaseConnectionWarmer.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 RollCallServer/src/main/java/cc/aspark/config/DatabaseConnectionWarmer.java diff --git a/RollCallServer/src/main/java/cc/aspark/config/DatabaseConnectionWarmer.java b/RollCallServer/src/main/java/cc/aspark/config/DatabaseConnectionWarmer.java new file mode 100644 index 0000000..b19ab46 --- /dev/null +++ b/RollCallServer/src/main/java/cc/aspark/config/DatabaseConnectionWarmer.java @@ -0,0 +1,35 @@ +package cc.aspark.config; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; + +@Slf4j +@Component +@RequiredArgsConstructor +public class DatabaseConnectionWarmer implements ApplicationRunner { + + private final DataSource dataSource; + + @Override + public void run(ApplicationArguments args) { + log.info("开始预热数据库连接池..."); + long startTime = System.currentTimeMillis(); + + try (Connection conn = dataSource.getConnection()) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("SELECT 1"); + } + log.info("数据库连接预热完成,耗时:{}ms", System.currentTimeMillis() - startTime); + } catch (SQLException e) { + log.error("数据库连接预热失败", e); + } + } +} \ No newline at end of file