快速刷新数据库配置 [英] Refresh database configuration on the fly
问题描述
我在属性文件中具有数据库配置:
I have database configuration in the properties file:
port=8080
host=host-default
主机默认显然是DNS。下面是我的配置类:
host-default is obviously DNS. Below is my configuration class:
@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单例,但无济于事。谢谢
So, there is a problem. When the server is running, and in meantime I change DNS the connection with DB will fall dawn. At this moment I cant refresh configuration. I can catch moment when DNS change but I cannot update config. Have you any idea? I tried to destroy DatabaseTemplate singleton but It does not help. Thanks
推荐答案
您将需要创建一个包装数据库连接的新bean,然后根据计划对其进行更新:
You will need to create a new bean that wraps the database connection, then update it based on a schedule :
@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
}
这篇关于快速刷新数据库配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!