spring boot 配置中心 apollo 动态修改mysql数据源

  • 转自 博客园文章
public class DynamicDataSource extends AbstractRoutingDataSource {
    public final static String DATASOURCE_TAG = "db";

    @Override
    protected Object determineCurrentLookupKey() {
        return DATASOURCE_TAG;
    }
}
@Configuration
@Slf4j
public class DataSourceConfig {
    @ApolloConfig
    private Config config;
    private final static String DATASOURCE_TAG = "db";

    @Autowired
    ApplicationContext context;


    @ApolloConfigChangeListener
    public void onChange(ConfigChangeEvent changeEvent) {
        Set<String> keys = changeEvent.changedKeys();
        long count = keys.stream().filter(key -> key.contains("spring.datasource")).count();
        if (count > 0) {
            DynamicDataSource dataSource = context.getBean(DynamicDataSource.class);
            dataSource.setTargetDataSources(Collections.singletonMap(DynamicDataSource.DATASOURCE_TAG, dataSource()));
            dataSource.afterPropertiesSet();
            log.info("finish to refresh datasource");
        }
    }

    @Bean("dataSource")
    public DynamicDataSource dynamicDataSource() {
        DynamicDataSource dataSource = new DynamicDataSource();
        dataSource.setTargetDataSources(Collections.singletonMap(DynamicDataSource.DATASOURCE_TAG, dataSource()));
        return dataSource;
    }

    private DataSource dataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(config.getProperty("spring.datasource.url", ""));
        dataSource.setUsername(config.getProperty("spring.datasource.username", ""));
        dataSource.setPassword(config.getProperty("spring.datasource.password", ""));
        return dataSource;
    }
}

你可能感兴趣的:(mysql,数据库,spring,boot)