我在属性文件中有数据库配置:
port=8080
host=host-default
host-default显然是DNS。以下是我的配置类:
@Configuration
@Slf4j
public class DatabaseConfig {
@Value("${port}")
private int port;
@Value("${host}")
private String hostname;
@Bean
public DatabaseTemplate databaseTemplate() {
try {
return new DatabaseTemplate(client());
} catch (Exception e) {
log.error("Ex: " + e.getMessage(), e);
return null;
}
}
@Bean
public Client client() throws UnknownHostException {
TransportAddress address = new InetSocketTransportAddress(InetAddress.getByName(this.hostname), this.port);
client.addTransportAddress(address);
return client;
}
}
所以,有一个问题。当服务器运行时,同时我更改DNS与DB的连接将会失败。此刻我无法刷新配置。我可以抓住DNS更改的时刻,但我无法更新配置。你知道吗?我试图破坏DatabaseTemplate单例,但它没有帮助。感谢
答案 0 :(得分:0)
您需要创建一个包装数据库连接的新bean,然后根据计划更新它:
@Component
public class DataSourceManager implements DataSource{
private DataSource dataSource;
@PostConstruct
@Scheduled(fixedRate=1000)
public void reload() {
// init the datasource
}
public DataSource getDataSource(String dbName) {
return dataSource;
}
@Override
public Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
.... wrap all the other DataSource methods
}