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