原理 :
apollo的部署
jdk 要求8以上
mysql 5.7以上
执行build.sh 这样就把configService,adminService 打包到对应的target下面
把这个放到linux下面执行解压出来 执行scripts 目录下面的start.sh
config里面是配置信息连接数据库的配置信息
protal项目里面要配置连接数据库的配置
这个文件是连接数据库的配置信息
客户端连接配置中心
<dependency> <groupId>com.ctrip.framework.apollo</groupId> <artifactId>apollo-client</artifactId> <version>1.1.0</version> </dependency>
这个jar包已经上传到了中央仓库可以直接用
配置多个namespace
动态改变数据源
package com.liuchao.mayikttest.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 com.zaxxer.hikari.HikariDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; 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; import java.util.Set; @Configuration @EnableConfigurationProperties(DataSourceProperties.class) public class DataSourceConfiguration { Logger logger = LoggerFactory.getLogger(getClass()); private final static String DATASOURCE_TAG = "db"; @Autowired ApplicationContext context; @ApolloConfig Config config; @Bean("dataSource") public DynamicDataSource dynamicDataSource() { DynamicDataSource source = new DynamicDataSource(); source.setTargetDataSources(Collections.singletonMap(DATASOURCE_TAG, dataSource())); return source; } @ApolloConfigChangeListener public void onChange(ConfigChangeEvent changeEvent) { Set<String> strings = changeEvent.changedKeys(); if (strings.contains("spring.datasource.primary.jdbc-url") || strings.contains("spring.datasource.primary.username") || strings.contains("spring.datasource.primary.password")) { DynamicDataSource source = context.getBean(DynamicDataSource.class); source.setTargetDataSources(Collections.singletonMap(DATASOURCE_TAG, dataSource())); source.afterPropertiesSet(); logger.info("动态切换数据源为:{}", config.getProperty("spring.datasource.url", "")); } } public DataSource dataSource() { HikariDataSource dataSource = new HikariDataSource(); dataSource.setJdbcUrl(config.getProperty("spring.datasource.primary.jdbc-url", "")); dataSource.setUsername(config.getProperty("spring.datasource.primary.username", "")); dataSource.setPassword(config.getProperty("spring.datasource.primary.password", "")); return dataSource; } class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DATASOURCE_TAG; } } }
修改部门信息