这是一个可以动态获取配置并生效,不用重启服务的框架。
https://github.com/apolloconfig/apollo-build-scripts
搭建方式就不多说了,参考文档
二、搭建一个spring boot项目(略) 三、spring boot mybatis多数据源配置我们准备好了一个Quick Start安装包,大家只需要下载到本地,就可以直接使用,免去了编译、打包过程。
安装包共50M,如果访问github网速不给力的话,可以从百度网盘下载。
从Github下载 checkout或下载apollo-build-scripts项目 从百度网盘下载 通过网盘链接下载,提取码: 9wwe
下载到本地后,在本地解压apollo-quick-start.zip 为啥安装包要58M这么大?
因为这是一个可以自启动的jar包,里面包含了所有依赖jar包以及一个内置的tomcat容器
@Configuration
//扫对应mapper interface 的包路径
@MapperScan(basePackages = "com.apollo.demo.mapper.read", sqlSessionTemplateRef = "readSqlSessionTemplate")
public class ReadMysqlConfig {
@Bean(name = "readDataSource")
//配置文件中数据库配置
@ConfigurationProperties(prefix = "spring.datasource.read")
public DataSource tefpDataSource() {
DruidDataSource dataSource = new DruidDataSource();
//将beanName放进map放便动态更新数据库配置
DataSourceConfig.dsreload.put("spring.datasource.read.url", "readDataSource");
return dataSource;
}
@Bean(name = "readSqlSessionFactory")
public SqlSessionFactory tefpSqlSessionFactory(@Qualifier("readDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
//mapper.xml文件路径
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/read*.xml
**/*.properties
true
DataSourceConfig中为什么要两次重启
DruidAbstractDataSource setUrl()方法只要初始化之后就不能修改了
public void setUrl(String jdbcUrl) {
if (StringUtils.equals(this.jdbcUrl, jdbcUrl)) {
return;
}
if (inited) {
throw new UnsupportedOperationException();
}
if (jdbcUrl != null) {
jdbcUrl = jdbcUrl.trim();
}
this.jdbcUrl = jdbcUrl;
// if (jdbcUrl.startsWith(ConfigFilter.URL_PREFIX)) {
// this.filters.add(new ConfigFilter());
// }
}
但是它的restart()方法会讲初始化状态恢复到false
public void restart() throws SQLException {
lock.lock();
try {
if (activeCount > 0) {
throw new SQLException("can not restart, activeCount not zero. " + activeCount);
}
if (LOG.isInfoEnabled()) {
LOG.info("{dataSource-" + this.getID() + "} restart");
}
this.close();
this.resetStat();
this.inited = false;
this.enable = true;
this.closed = false;
} finally {
lock.unlock();
}
}



