标签:tar object 比较 原理 vat determine word creat turn
Spring提供了AbstractRoutingDataSource用于动态路由数据源,第一种场景继承AbstractRoutingDataSource类并覆写其protected abstract Object determineCurrentLookupKey()即可;
而第二种场景我们直接覆写protected DataSource determineTargetDataSource方法即可。原理可看下AbstractRoutingDataSource对应源码,比较简单,不做赘述。
直接上干货:
public class DynamicDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal<DataSource> dataSource = ThreadLocal.withInitial(() -> (DataSource) SpringUtils.getBean("defaultDataSource"));
public static void setDataSource(DataSource dataSource) {
DynamicDataSource.dataSource.set(dataSource);
}
public static DataSource getDataSource() {
return DynamicDataSource.dataSource.get();
}
@Override
protected Object determineCurrentLookupKey() {
return null;
}
@Override
protected DataSource determineTargetDataSource() {
return getDataSource();
}
public static void clear() {
DynamicDataSource.dataSource.remove();
}
}
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.druid")
public DataSource defaultDataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean
@Primary
public DynamicDataSource dataSource() {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
dynamicDataSource.setTargetDataSources(new HashMap<>());
return dynamicDataSource;
}
}
附上详细使用方法:
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl("jdbc:mysql://localhost:3306/sys?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&useAffectedRows=true");
druidDataSource.setUsername("root");
druidDataSource.setPassword("root");
DynamicDataSource.setDataSource(druidDataSource);
此时数据源已切换到druidDataSource ,调用自己的业务方法即可。
使用完后调用DynamicDataSource.clear();重置为默认数据源。
标签:tar object 比较 原理 vat determine word creat turn
原文地址:https://www.cnblogs.com/tswhq/p/11668078.html