多数据源注解配置及调用过程

多数据源注解:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
String name() default “”;
}
切面处理类:
@Aspect
@Component
public class DataSourceAspect implements Ordered {
protected Logger logger = LoggerFactory.getLogger(getClass());

@Pointcut("@annotation(datasources.annotation.DataSource)")
public void dataSourcePointCut() {

}

@Around("dataSourcePointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
    System.out.println("around()......................................");
    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();

    DataSource ds = method.getAnnotation(DataSource.class);
    if(ds == null){
        DynamicDataSource.setDataSource(DataSourceNames.FIRST);
        logger.debug("set datasource is " + DataSourceNames.FIRST);
    }else {
        DynamicDataSource.setDataSource(ds.name());
        logger.debug("set datasource is " + ds.name());
    }

    try {
        System.out.println("return......................................");
        return point.proceed();
    } finally {
        System.out.println("finally..............................");
        DynamicDataSource.clearDataSource();
        logger.debug("clean datasource");
    }
}

@Override
public int getOrder() {
    return 1;
}

}
添加数据源,统一配置:
public interface DataSourceNames {
String FIRST = “first”;
String SECOND = “second”;

}
动态写入数据源:
public class DynamicDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal contextHolder = new ThreadLocal<>();

public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
    super.setDefaultTargetDataSource(defaultTargetDataSource);
    super.setTargetDataSources(targetDataSources);
    super.afterPropertiesSet();
}

@Override
protected Object determineCurrentLookupKey() {
    return getDataSource();
}

public static void setDataSource(String dataSource) {
    contextHolder.set(dataSource);
}

public static String getDataSource() {
    return contextHolder.get();
}

public static void clearDataSource() {
    contextHolder.remove();
}

}
springboot下配置多数据源:
@Configuration
public class DynamicDataSourceConfig {

@Bean
@ConfigurationProperties("spring.datasource.druid.first")
public DataSource firstDataSource(){
    return DruidDataSourceBuilder.create().build();
}

@Bean
@ConfigurationProperties("spring.datasource.druid.second")
public DataSource secondDataSource(){
    return DruidDataSourceBuilder.create().build();
}

@Bean
@Primary
public DynamicDataSource dataSource(DataSource firstDataSource, DataSource secondDataSource) {
    Map<Object, Object> targetDataSources = new HashMap<>();
    targetDataSources.put(DataSourceNames.FIRST, firstDataSource);
    targetDataSources.put(DataSourceNames.SECOND, secondDataSource);
    return new DynamicDataSource(firstDataSource, targetDataSources);
}

}
配置文件配置:
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
druid:
first: #数据源1
url: jdbc:mysql://localhost:3306/db?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
username: root
password: **
second: #数据源2
url: jdbc:mysql://localhost:3306/db?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
username: root
password: *
调用过程:
1、
@DataSource(name = DataSourceNames.SECOND)
public SysUserEntity queryUser2(Long userId){
System.out.println(“SysUserEntity……………………..”);
return sysUserService.selectById(userId);
}

2、
@Around(“dataSourcePointCut()”)
public Object around(ProceedingJoinPoint point) throws Throwable {
System.out.println(“around()………………………………..”);
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();

    DataSource ds = method.getAnnotation(DataSource.class);
    if(ds == null){
        DynamicDataSource.setDataSource(DataSourceNames.FIRST);
        logger.debug("set datasource is " + DataSourceNames.FIRST);
    }else {
        DynamicDataSource.setDataSource(ds.name());
        logger.debug("set datasource is " + ds.name());
    }

    try {
        System.out.println("return......................................");
        return point.proceed();
    } finally {
        System.out.println("finally..............................");
        DynamicDataSource.clearDataSource();
        logger.debug("clean datasource");
    }
}       
3、
public class DynamicDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
    super.setDefaultTargetDataSource(defaultTargetDataSource);
    super.setTargetDataSources(targetDataSources);
    super.afterPropertiesSet();
}

@Override
protected Object determineCurrentLookupKey() {
    return getDataSource();
}

public static void setDataSource(String dataSource) {
    **contextHolder.set(dataSource);**
}

public static String getDataSource() {
    return contextHolder.get();
}

public static void clearDataSource() {
    contextHolder.remove();
}     
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值