集成Apollo
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.4.0</version>
</dependency>
在项目启动主类上添加 @EnableApolloConfig
# 在 application.yml 中,添加以下配置
app:
id: aiop-cmdb-job #在Apollo中的唯一id,可以为项目名或不重复的数字,要与启动起来的apollo服务对应
apollo:
meta: http://localhost:8080 # 在 portal==》apollo-env.properties中配置的对应的meta
配置动态刷新数据库
package aiop.cmdb.job.config;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.Collections;
/**
* @author lisongyu
* @date 2020/01/17
*/
@Configuration
@Slf4j
public class DataSourceConfiguration {
private final static String DATASOURCE_TAG = "db";
@Autowired
ApplicationContext context;
@ApolloConfig
Config config;
@Bean
public DynamicDataSource dynamicDataSource() {
DynamicDataSource source = new DynamicDataSource();
source.setTargetDataSources(Collections.singletonMap(DATASOURCE_TAG, dataSource()));
return source;
}
@ApolloConfigChangeListener(interestedKeyPrefixes = {"spring.datasource","spring.rabbitmq","jedis.pool"})
public void onChange(ConfigChangeEvent changeEvent) {
changeEvent.changedKeys().forEach(s -> {
DynamicDataSource source = context.getBean(DynamicDataSource.class);
source.setTargetDataSources(Collections.singletonMap(DATASOURCE_TAG, dataSource()));
source.afterPropertiesSet();
log.info("动态切换数据源为:{}", config.getProperty("spring.datasource.url", ""));
});
}
public DataSource dataSource() {
DataSourceProperties dataSource = new DataSourceProperties();
dataSource.setUrl(config.getProperty("spring.datasource.url", ""));
dataSource.setUsername(config.getProperty("spring.datasource.username", ""));
dataSource.setPassword(config.getProperty("spring.datasource.password", ""));
return dataSource.initializeDataSourceBuilder().build();
}
class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DATASOURCE_TAG;
}
}
}
原文:https://www.cnblogs.com/lisongyu/p/12213481.html