一、配置文件 aop: maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.1.7.RELEASE</version>
</dependency>
spring.datasource.db01.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.db01.jdbc-url=jdbc:mysql://192.168.1.32:3306/db1?useUnicode=true&allowMultiQueries=true&characterEncoding=utf-8&serverTimezone=GMT
spring.datasource.db01.username=root
spring.datasource.db01.password=123
spring.datasource.db02.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.db02.jdbc-url=jdbc:mysql://192.168.1.32:3306/db2?useUnicode=true&allowMultiQueries=true&characterEncoding=utf-8&serverTimezone=GMT
spring.datasource.db02.username=root
spring.datasource.db02.password= 123
二、数据源配置文件
package com.plus.config.dataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DataSourceConfig {
@Bean(name = "firstAopDataSource")
@ConfigurationProperties(prefix = "spring.datasource.db01")
public DataSource firstDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondAopDataSource")
@ConfigurationProperties(prefix = "spring.datasource.db02")
public DataSource secondDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "dynamicDataSource")
@Primary
public DataSource dynamicDataSource() {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
dynamicDataSource.setDefaultTargetDataSource(firstDataSource());
Map<Object, Object> dataSourceMap = new HashMap<>();
dataSourceMap.put("firstAopDataSource", firstDataSource());
dataSourceMap.put("secondAopDataSource", secondDataSource());
dynamicDataSource.setTargetDataSources(dataSourceMap);
return dynamicDataSource;
}
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dynamicDataSource());
}
}
三、DynamicDataSource
package com.plus.config.dataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
log.info("DynamicDataSource.determineCurrentLookupKey curr data source :" + DynamicDataSourceHolder.getDataSource());
return DynamicDataSourceHolder.getDataSource();
}
}
四、DynamicDataSourceHolder
package com.plus.config.dataSource;
public class DynamicDataSourceHolder {
private static final ThreadLocal<String> THREAD_LOCAL = new ThreadLocal<String>();
public static void setDataSource(String dataSource){
THREAD_LOCAL.set(dataSource);
}
public static String getDataSource() {
return THREAD_LOCAL.get();
}
public static void clear() {
THREAD_LOCAL.remove();
}
}
五、自定义注解
package com.plus.config.dataSource;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
String value() default "";
}
六、切面 1、切面的实现方式1,这种实现方式有个问题,就是方法中多次切换数据源会有问题。
package com.plus.config.dataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Aspect
@Component
@Slf4j
@Order(1)
public class DataSourceAspect {
private final String defultDataSource = "firstAopDataSource";
@Pointcut("execution( * com.plus.*..*.*(..))")
public void dataSourcePoint() {}
@Before("dataSourcePoint()")
public void before(JoinPoint joinPoint) {
Object target = joinPoint.getTarget();
MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
String methodName = methodSignature.getName();
Class[] parameterTypes = methodSignature.getParameterTypes();
try {
Method method = target.getClass().getInterfaces()[0].getMethod(methodName, parameterTypes);
String dataSource = defultDataSource;
if (null != method && method.isAnnotationPresent(TargetDataSource.class)) {
TargetDataSource targetDataSource = method.getAnnotation(TargetDataSource.class);
dataSource = targetDataSource.value();
DynamicDataSourceHolder.setDataSource(dataSource);
}
log.info("当前数据源是: " + dataSource);
} catch (Exception e) {
log.info("error", e);
}
}
@After("dataSourcePoint()")
public void after(JoinPoint joinPoint) {
DynamicDataSourceHolder.clear();
}
}
2、切面实现方式2,一个方法中可以切换多次数据源
@Aspect
@Order(1)
@Component
public class DynamicDataSourceAspect {
@Around("@annotation(targetDataSource)")
public Object Around(ProceedingJoinPoint pjp, DataSource targetDataSource) throws Throwable {
String lastDbType = DataSourceContextHolder.getDBType();
long tid = Thread.currentThread().getId();
String methodName = "";
Signature signature = pjp.getSignature();
if(signature != null){
methodName = signature.getName();
}
LogFactory.sailInfo("切换数据源,lastDbType:{},tid:{},methodName:{}", lastDbType,tid,methodName);
String dataSourceKey = targetDataSource.value();
DataSourceContextHolder.setDBType(dataSourceKey);
LogFactory.sailInfo("设置数据源为 {},tid:{},methodName:{}", dataSourceKey,tid,methodName);
Object ret = null;
try {
ret = pjp.proceed();
}finally {
LogFactory.sailInfo("执行方法完毕,当前数据源:{},tid:{},methodName:{}", DataSourceContextHolder.getDBType(),tid,methodName);
LogFactory.sailInfo("恢复上次数据源:{},tid:{},methodName:{}", lastDbType,tid,methodName);
DataSourceContextHolder.setDBType(lastDbType);
}
return ret;
}
}
修改启动类
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class Myapplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Myapplication.class,args);
System.out.println("========");
}
}
七、测试代码 Controlle:
@PostMapping("/vehicleSelect")
public ResultData<?> vehicleSelect(@RequestParam("id") @NotNull(message = "id不能为空") Integer id){
List<CarVehiclePo> carVehicleSelect=service.vehicleSelect(id);
return ResultData.result(carVehicleSelect);
}
@PostMapping("/vehicleSelect2")
public ResultData<?> vehicleSelect2(){
List<CarVehiclePo> carVehicleSelect=service.vehicleSelect2();
return ResultData.result(carVehicleSelect);
}
service: 注解目前我用在service 接口上了
List<CarVehiclePo> vehicleSelect(Integer id);
@TargetDataSource(value = "secondAopDataSource")
List<CarVehiclePo> vehicleSelect2();
impl: 用的是mybatisplus
@Service("iCarVehicleService")
public class CarVehicleServiceImpl extends ServiceImpl<CarVehicleMapper, CarVehiclePo> implements ICarVehicleService {
@Override
public List<CarVehiclePo> vehicleSelect(Integer id) {
List<CarVehiclePo> list = list(new LambdaQueryWrapper<>());
return list;
}
@Override
public List<CarVehiclePo> vehicleSelect2() {
List<CarVehiclePo> list = list(new LambdaQueryWrapper<CarVehiclePo>()
.eq(CarVehiclePo::getId,23));
return list;
}
}
两个地址结果筛选的数据是不一样的
使用中遇到的问题
1、首先就是一个服务中存在多次切库的情况。按照切面1的实现方式,是存在问题的。如果使用around切面的话,可以解决这个问题。个人觉得事务可以加在Mapper上或者Dao上,不要加在Service。如果需要,在考虑加在Service。目前我用在service 接口上了 。每次访问带注解方法时会有数据源切换问题,的通过断点可以看出,不知道为什么,你们知道记得告诉我
按照切面1的实现方式,启动会有错误信息,但不影响功能, Method method =target.getClass().getInterfaces([0].getMethod(methodName,parameterTypes); 这一行报错
2、事务问题。在一个事务中,无法进行切库。原因的话,这里不解释了
可以参考我另一篇MyBatis-Plus 注解切换 多数据源: https://blog.csdn.net/qq_41080067/article/details/124347901
|