[add] 增加了备用数据库切换

This commit is contained in:
LYC 2025-04-30 18:55:50 +08:00
parent a31aa8df17
commit bc01f0a680
1 changed files with 30 additions and 0 deletions

View File

@ -0,0 +1,30 @@
package com.waterquality.projectmanagement.config.database;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;
@Component
public class MasterHealthChecker {
@Autowired
@Qualifier("masterDataSource")
private DataSource masterDataSource;
// 每60秒检查一次主库
@Scheduled(fixedRate = 60000)
public void checkMasterHealth() {
try (Connection conn = masterDataSource.getConnection();
Statement stmt = conn.createStatement()) {
stmt.execute("SELECT 1"); // 执行简单查询检测主库
DynamicRoutingDataSource.setMasterAvailable(true);
} catch (Exception e) {
DynamicRoutingDataSource.setMasterAvailable(false); // 主库不可用
}
}
}