1、DataSourceContextHolder
public class DataSourceContextHolder {
private static final Logger log = LoggerFactory.getLogger(DataSourceContextHolder.class);
/**
* 默认数据源
*/
static final String DEFAULT_DS = "db-read";
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
// 设置数据源名
public static void setDB(String dbType) {
log.info("切换到{}数据源", dbType);
contextHolder.set(dbType);
}
// 获取数据源名
static String getDB() {
return contextHolder.get();
}
// 清除数据源名
static void clearDB() {
contextHolder.remove();
}
}
2、DataSourceExampleConfig
@Configuration
@MapperScan(basePackages = {
"com.example.common.dao.example" }, sqlSessionFactoryRef = "exampleSqlSessionFactory", sqlSessionTemplateRef = "exampleSqlSessionTemplate")
public class DataSourceExampleConfig {
@Primary
@Bean(name = "exampleDataSource")
@ConfigurationProperties(prefix = "spring.datasource.example")
public DataSource exampleDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "exampleReadDataSource")
@ConfigurationProperties(prefix = "spring.datasource.example.read")
public DataSource exampleReadDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "dynamicSource")
public DynamicDataSource dynamicSource(@Qualifier("exampleDataSource") DataSource exampleDataSource,
@Qualifier("exampleReadDataSource") DataSource exampleReadDataSource) {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
// 默认数据源
dynamicDataSource.setDefaultTargetDataSource(exampleReadDataSource);
// 配置多数据源
Map<Object, Object> dsMap = new HashMap<>();
dsMap.put("db-master", exampleDataSource);
dsMap.put("db-read", exampleReadDataSource);
dynamicDataSource.setTargetDataSources(dsMap);
return dynamicDataSource;
}
@Bean(name = "exampleSqlSessionFactory")
public SqlSessionFactory exampleSqlSessionFactory(@Qualifier("dynamicSource") DataSource dynamicSource)
throws Exception { // NOSONAR
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dynamicSource);
sqlSessionFactoryBean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath:mappers/example/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public DataSourceTransactionManager exampleTransactionManager(
@Qualifier("dynamicSource") DataSource dynamicSource) { // NOSONAR
return new DataSourceTransactionManager(dynamicSource);
}
@Bean(name = "exampleSqlSessionTemplate")
public SqlSessionTemplate exampleSqlSessionTemplate(
@Qualifier("exampleSqlSessionFactory") SqlSessionFactory sqlSessionFactory) { // NOSONAR
return new SqlSessionTemplate(sqlSessionFactory);
}
}
3、DbKey
public class DbKey {
/**
* 读数据库
*/
public static final String DBREAD = "db-read";
/**
* 写数据库
*/
public static final String DBMASTER = "db-master";
private DbKey() {
}
}
4、DynamicDataSource
public class DynamicDataSource extends AbstractRoutingDataSource {
private static final Logger log = LoggerFactory.getLogger(DynamicDataSource.class);
@Override
protected Object determineCurrentLookupKey() {
log.debug("数据源为{}", DataSourceContextHolder.getDB());
return DataSourceContextHolder.getDB();
}
}
5、DynamicDataSourceAspect
@Aspect
@Component
public class DynamicDataSourceAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSourceAspect.class);
@SuppressWarnings("rawtypes")
@Before("execution(* com.example.manage.controller..*.*(..))")
public void beforeSwitchDS(JoinPoint point) {
// 获得当前访问的class
Class<?> clazz = point.getTarget().getClass();
// 获得访问的方法名
String methodName = point.getSignature().getName();
// 得到方法的参数的类型
Class[] argClass = ((MethodSignature) point.getSignature()).getParameterTypes();
String dataSource = DataSourceContextHolder.DEFAULT_DS;
try {
// 得到访问的方法对象
Method method = clazz.getMethod(methodName, argClass);
// 判断是否存在@DS注解
if (method.isAnnotationPresent(DBSource.class)) {
DBSource annotation = method.getAnnotation(DBSource.class);
// 取出注解中的数据源名
dataSource = annotation.value();
}
} catch (Exception e) {
LOGGER.error("beforeSwitchDS error", e);
}
// 切换数据源
DataSourceContextHolder.setDB(dataSource);
}
@After("execution(* com.example.manage.controller..*.*(..))")
public void afterSwitchDS(JoinPoint point) {
DataSourceContextHolder.clearDB();
}
}
6 切点 DBSource
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface DBSource {
String value() default "db-master";
}
7、application.properties 配置(@@是配置文件里获取的)
#写配置
spring.datasource.example.url=@spring.datasource.example.url@
spring.datasource.example.username=@spring.datasource.example.username@
spring.datasource.example.password=@spring.datasource.example.password@
spring.datasource.example.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.example.remove-abandoned-timeout=180
spring.datasource.example.testOnReturn=false
spring.datasource.example.initial-size=2
spring.datasource.example.min-evictable-idle-time-millis=300000
spring.datasource.example.max-active=20
spring.datasource.example.testWhileIdle=true
spring.datasource.example.min-idle=1
spring.datasource.example.poolPreparedStatements=true
spring.datasource.example.testOnBorrow=false
spring.datasource.example.max-wait=60000
spring.datasource.example.time-between-eviction-runs-millis=3000
spring.datasource.example.max-idle=10
spring.datasource.example.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.example.remove-abandoned=true
spring.datasource.example.connection-properties=clientEncoding=UTF-8
spring.datasource.example.default-auto-commit=true
spring.datasource.example.validation-query=select 1
#读配置
spring.datasource.example.read.url=@spring.datasource.example.read.url@
spring.datasource.example.read.username=@spring.datasource.example.read.username@
spring.datasource.example.read.password=@spring.datasource.example.read.password@
spring.datasource.example.read.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.example.read.remove-abandoned-timeout=180
spring.datasource.example.read.testOnReturn=false
spring.datasource.example.read.initial-size=2
spring.datasource.example.read.min-evictable-idle-time-millis=300000
spring.datasource.example.read.max-active=20
spring.datasource.example.read.testWhileIdle=true
spring.datasource.example.read.min-idle=1
spring.datasource.example.read.poolPreparedStatements=true
spring.datasource.example.read.testOnBorrow=false
spring.datasource.example.read.max-wait=60000
spring.datasource.example.read.time-between-eviction-runs-millis=3000
spring.datasource.example.read.max-idle=10
spring.datasource.example.read.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.example.read.remove-abandoned=true
spring.datasource.example.read.connection-properties=clientEncoding=UTF-8
spring.datasource.example.read.default-auto-commit=true
spring.datasource.example.read.validation-query=select 1
切换举例子,PS 目前由于事务的原因,注解是放在了controller上,这就局限了此方法及调用的service用同一个数据源。如果有更好的解决方案,请赐教
@PostMapping("***")
@ApiOperation(value = "启用/禁用***的状态", response = Response.class, notes = "启用/禁用***的状态")
@DBSource(DbKey.DBMASTER)
public Response<Object> reviseListState(@RequestBody ReviseListStateParam reviseListStateParam) {
listService.reviseListState(reviseListStateParam);
return Response.R200;
}