问题
I have database configuration in the properties file:
port=8080
host=host-default
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;
}
}
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
回答1:
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
}
来源:https://stackoverflow.com/questions/44716195/refresh-database-configuration-on-the-fly