配置文件方式,這里使用YMAL砖织,你也可以使用傳統(tǒng)的Properties,只要將:更換為.的形式即可慕购。
spring:
datasource:
one:
setype: com.alibaba.druid.pool.DruidDataSource
url: 你的JDBC URL
username: 你的用戶名
password: 你的密碼
driver-class-name: com.mysql.jdbc.Driver
two:
setype: com.alibaba.druid.pool.DruidDataSource
url: 你的JDBC URL
username: 你的用戶名
password: 你的密碼
driver-class-name: com.mysql.jdbc.Driver
創(chuàng)建DynamicDataSource
類
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getType();
}
}
創(chuàng)建DataSourceContextHolder
類并使用ThreadLocal
來(lái)存放數(shù)據(jù)源類型變量
public class DataSourceContextHolder {
private static final Logger LOGGER = LoggerFactory.getLogger(ProductContextHolder.class);
public static final List<Object> supportList= new ArrayList<>();
// 線程本地環(huán)境
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static void setType(String type) {
contextHolder.set(type);
LOGGER.debug("==============切換數(shù)據(jù)源拳昌,類型:" + type + "================");
}
public static String getType() {
return (contextHolder.get());
}
public static void clear() {
contextHolder.remove();
}
public static boolean support(String type) {
return supportList.contains(type);
}
}
創(chuàng)建一個(gè)Configurer
來(lái)配置數(shù)據(jù)源惜犀,這里僅配置兩個(gè)作為參考捺氢,如果你看過(guò) 使用Spring配置動(dòng)態(tài)數(shù)據(jù)源實(shí)現(xiàn)讀寫分離 的話惜姐,你會(huì)覺得這非常簡(jiǎn)單牵敷,只不過(guò)是XML配置方式 =》 編程配置方式的轉(zhuǎn)化胡岔。
有趣的是如果你要使用非默認(rèn)數(shù)據(jù)源,如Druid枷餐,數(shù)據(jù)源配置項(xiàng)datasource.setype.com.alibaba.druid.pool.DruidDataSource
并不能很好工作靶瘸,只能使用DataSourceBuilder
的時(shí)候顯式指定,至少在Spring Boot 1.4是這樣毛肋。
@Configuration
public class DataSourceConfigurer {
@Bean
@Primary
@ConfigurationProperties(prefix="spring.datasource.one")
public DataSource oneDataSource() {
return DataSourceBuilder
.create()
.type(DruidDataSource.class)
.build();
}
@Bean
@ConfigurationProperties(prefix="spring.datasource.two")
public DataSource twoDataSource() {
return DataSourceBuilder
.create()
.type(DruidDataSource.class)
.build();
}
@Bean
public DynamicDataSource dataSource(){
DynamicDataSource dynamicDataSource = new DynamicDataSource();
Map<Object, Object> targetDataSources = Maps.newHashMap();
targetDataSources.put("one", oneDataSource());
targetDataSources.put("two", twoDataSource());
dynamicDataSource.setTargetDataSources(targetDataSources);
DataSourceContextHolder.supportList.addAll(targetDataSources.keySet());
return dynamicDataSource;
}
}
好了怨咪,動(dòng)態(tài)數(shù)據(jù)源配置完成,至于在什么時(shí)候切換數(shù)據(jù)源根據(jù)你的實(shí)際情況而定润匙,方式有很多诗眨,比如使用注解、做切面孕讳、用攔截器攔截參數(shù)等等匠楚,這里就不做贅述了。在使用void DataSourceContextHolder.setType(String type)
切換數(shù)據(jù)源前最好能調(diào)用boolean DataSourceContextHolder.support(String type)
判斷是否支持該數(shù)據(jù)源厂财。