springboot动态切换多数据源-自定义注解方式

1、多数据源参数配置文件(必须是yaml文件)
spring:
  datasource:
    master:
      username: xxxx
      password: xxxx
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://x.x.x.x:x/x
    slave:
      username: xxxx
      password: xxxx
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://x.x.x.x:x/x
    type: com.alibaba.druid.pool.DruidDataSource
2、数据源切换处理
public class DataSourceContextHolder{
    public static final String MASTER = "master";
    public static final String SLAVE = "slave";
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();


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

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

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

3、继承AbstractRoutingDataSource
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.getDataSource();
    }
}

4、注入数据源
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
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 javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class MultipleDataSourceConfig {

    @Bean(DataSourceContextHolder.MASTER)
    @ConfigurationProperties("spring.datasource.master")
    public DataSource remoteDataSource(){
        return new DruidDataSource();
    }

    @Bean(DataSourceContextHolder.SLAVE)
    @ConfigurationProperties("spring.datasource.slave")
    public DataSource localDataSource(){
        return new DruidDataSource();
    }

  /**
     * 设置动态数据源,通过@Primary 来确定主DataSource
     *
     * @return
     */
    @Bean
    @Primary
    public DataSource createDynamicDataSource(@Qualifier(DataSourceContextHolder.MASTER) DataSource master, @Qualifier(DataSourceContextHolder.SLAVE) DataSource slave){
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setDefaultTargetDataSource(master);
        Map<Object,Object> map = new HashMap<>();
        map.put(DataSourceContextHolder.MASTER,master);
        map.put(DataSourceContextHolder.SLAVE,slave);
        dynamicDataSource.setTargetDataSources(map);
        return dynamicDataSource;
    }
}

5、自定义多数据源切换注解
import java.lang.annotation.*;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
    String value() default DataSourceContextHolder.MASTER;
}

6、AOP拦截类的实现
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Order(1)
@Component
public class DataSourceAspect {
    @Pointcut("@annotation(com.zzpt.multiDS.DataSource)")
    public void dsPointCut(){

    }

    @Before(value ="dsPointCut()")
    public void switchDataSource(JoinPoint joinPoint){
        DataSource dataSource = ((MethodSignature)joinPoint.getSignature()).getMethod().getAnnotation(com.zzpt.multiDS.DataSource.class);
        if (dataSource==null){
            return;
        }
        DataSourceContextHolder.setDataSource(dataSource.value());
    }
    @After(value = "dsPointCut()")
    public void after(){
        DataSourceContextHolder.clear();
        DataSourceContextHolder.setDataSource("master");
    }
}

注:若在启动项目的过程中会发生循环依赖的问题,直接修改启动类即可

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值