Refresh database configuration on the fly

人盡茶涼 提交于 2019-12-11 04:24:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!