SpringBoot配置多数据源(druid)

分析

spring本身是支持多数据源动态切换的,AbstractRoutingDataSource这个抽象类就是spring提供的一个数据源路由的一个入口,该抽象类暴露了一个determineCurrentLookupKey()的方法,该方法返回值是Object,该返回值作为key去取Map中的DataSource。

  • AbstractRoutingDataSource
    • getConnection()
      • determineTargetDataSource() 从Map中通过key获取DataSource
        • determineCurrentLookupKey() 获取key

1.创建一个线程线程安全的Holder来切换Key

public class DynamicDataSourceHolder {

    public static ThreadLocal<DataSourceKey> keyThreadLocal = new ThreadLocal<>();

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

    public static void set(DataSourceKey key){
        keyThreadLocal.set(key);
    }

    public static DataSourceKey get(){
        DataSourceKey key = keyThreadLocal.get();
        return null==key?DataSourceKey.DB:key;
    }

}

2.继承AbstractRoutingDataSource设置key

public class DynamicRoutingDataSource extends AbstractRoutingDataSource{
    @Nullable
    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceHolder.get();
    }
}

3.编写Config来初始化DataSource

@Configuration
public class DynamicDatasourceConfig {

    @Autowired
    ApplicationContext applicationContext;

    @Bean("druid_db")//必须加上该注解,否则 @ConfigurationProperties无效
    @ConfigurationProperties(prefix = "dynamic-datasource.druid-datasources.db")
    public DataSource db(StandardEnvironment env){
        DruidDataSource druidDataSource = DruidDataSourceBuilder.create().build();
        return common(env,druidDataSource);
    }
    @Bean("druid_db1")
    @ConfigurationProperties(prefix = "dynamic-datasource.druid-datasources.db1")
    public DataSource db1(StandardEnvironment env){
        DruidDataSource druidDataSource = DruidDataSourceBuilder.create().build();
        return common(env,druidDataSource);
    }
    @Bean("druid_db2")
    @ConfigurationProperties(prefix = "dynamic-datasource.druid-datasources.db2")
    public DataSource db2(StandardEnvironment env){
        DruidDataSource druidDataSource = DruidDataSourceBuilder.create().build();
        return common(env,druidDataSource);
    }

    @Bean("dataSource")
    public DataSource dynamicDataSource(StandardEnvironment env) {
        DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();
        Map<Object,Object> map = new HashMap<>();
        map.put(DataSourceKey.DB,applicationContext.getBean("druid_db"));
        map.put(DataSourceKey.DB1,applicationContext.getBean("druid_db1"));
        map.put(DataSourceKey.DB2,applicationContext.getBean("druid_db2"));
        dynamicRoutingDataSource.setDefaultTargetDataSource(applicationContext.getBean("druid_db"));
        dynamicRoutingDataSource.setTargetDataSources(map);
        return dynamicRoutingDataSource;
    }

    public DataSource common(StandardEnvironment env, DruidDataSource druidDataSource){
        Properties properties = new Properties();
        PropertySource<?> appProperties =  env.getPropertySources().get("applicationConfig: [classpath:/application.yml]");
        Map<String,Object> source = (Map<String, Object>) appProperties.getSource();
        properties.putAll(source);
        druidDataSource.configFromPropety(properties);
        return druidDataSource;
    }

}

4.通过aop动态去切换key

该注解确定的该方法使用哪一个数据源

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TargetDataSource {
    DataSourceKey value() default DataSourceKey.DB;
}

数据源的key

public enum  DataSourceKey {
    DB,DB1,DB2,DB3,DB4;
}

一个是拦截特定的方法和拦截有TargetDataSource注解的方法去动态切换

@Aspect
@Component
@Order(-100)//提高优先级
public class DynamicDataSourceAop {

    @Pointcut(value = "execution(public * com.yzz.boot..*.mapper ..*.*(..))")
    public void defaultDataSource(){}

    @Before(value = "defaultDataSource()")
    public void setDefaultDataSource(){

    }
    //没有注解,就选择默认的数据源
    @Before(value = "@annotation(dataSource)&&defaultDataSource()")
    public void setDynamicDataSource(TargetDataSource dataSource){
        if (null == dataSource){
            System.err.println("设置默认数据源"+DataSourceKey.DB);
            DynamicDataSourceHolder.set(DataSourceKey.DB);
        }else {
            System.err.println("切换数据源"+dataSource.value());
            DynamicDataSourceHolder.set(dataSource.value());
        }
    }
//清除该线程当前的数据
    @After(value = "defaultDataSource()&&@annotation(com.yzz.boot.dyConfig.ann.TargetDataSource)")
    public void clean(){
        System.err.println("清除当前线程的数据源");
        DynamicDataSourceHolder.clear();
    }
}

5.Mapper通过方法上通过注解去动态选择数据源

@Mapper
public interface TestMapper {
    @TargetDataSource(value = DataSourceKey.DB1)
    @Select("select * from t_es_test limit 5")
    List<HashMap> getAll();

    @TargetDataSource(value = DataSourceKey.DB2)
    @Select("select * from t_es_test limit 5")
    List<HashMap> getAll1();
}

6.程序入口去除默认的连接池的配置类

//去除默认的连接池
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
//扫描响应的包
@MapperScan("com.yzz.boot.*.mapper")
public class BootApplication {

    public static void main(String[] args) {
        SpringApplication.run(BootApplication.class);
    }
}

7.配置文件

spring:
  profiles:
    active: system

dynamic-datasource:
  druid:
    filters: stat
    maxActive: 20
    initialSize: 1
    maxWait: 30000
    minIdle: 10
    maxIdle: 15
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    maxOpenPreparedStatements: 20
    removeAbandoned: true
    removeAbandonedTimeout: 1800
    logAbandoned: true
  druid-datasources:
    db:
      url: jdbc:mysql://192.168.1.12:3306/yzz
      username: root
      password: root
      driver-class-name: com.mysql.jdbc.Driver
    db1:
      url: jdbc:mysql://192.168.1.12:3306/yzz
      username: root
      password: root
      driver-class-name: com.mysql.jdbc.Driver
    db2:
      url: jdbc:mysql://192.168.1.12:3306/yzz
      username: root
      password: root
      driver-class-name: com.mysql.jdbc.Driver


jdbc-conn:
      url: jdbc:mysql://192.168.1.12:3306/yzz
      username: root
      password: root
      driver-class-name: com.mysql.jdbc.Driver

总结

通过注解来动态原则key,spring的DataSource路由选择器通过key从之前设置进去的DataSource Map中获取响应的DataSource,从而达到了动态切换的目的。通过ThreadLocal来存储key,保证了数=数据在多线程环境下的正确性。

Spring Boot可以通过配置多个数据源来实现多数据源的使用,而Druid是一种数据库连接池,可以提供对多个数据源的连接管理和监控功能。 首先,在`pom.xml`文件中添加Druid和对应数据库驱动的依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> </dependency> <!-- 添加其他数据库驱动的依赖 --> ``` 然后,在`application.properties`或`application.yml`中配置多个数据源的相关信息,例如: ```properties # 主数据源 spring.datasource.url=jdbc:mysql://localhost:3306/db1 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # 第二个数据源 spring.datasource.second.url=jdbc:mysql://localhost:3306/db2 spring.datasource.second.username=root spring.datasource.second.password=123456 spring.datasource.second.driver-class-name=com.mysql.cj.jdbc.Driver ``` 接下来,创建多个数据源配置类,例如: ```java @Configuration public class DataSourceConfig { @Primary @Bean(name = "dataSource") @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource() { return DruidDataSourceBuilder.create().build(); } @Bean(name = "secondDataSource") @ConfigurationProperties(prefix = "spring.datasource.second") public DataSource secondDataSource() { return DruidDataSourceBuilder.create().build(); } } ``` 注意,`@Primary`注解用于标识默认的主数据源。 最后,在需要使用数据源的地方,通过`@Qualifier`注解指定要使用的数据源,例如: ```java @Service public class MyService { @Autowired @Qualifier("dataSource") private DataSource dataSource; // 使用dataSource进行数据库操作 @Autowired @Qualifier("secondDataSource") private DataSource secondDataSource; // 使用secondDataSource进行数据库操作 } ``` 这样就完成了Spring Boot中多数据源Druid配置。在使用数据源时,可以根据需要在不同的地方注入不同的数据源
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值