SpringBoot基于注解形式配置多数据源@DS

@TOC()

1.引入依赖

      <!-- dynamic-datasource 多数据源-->
      <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
        <version>3.5.2</version>
      </dependency>

2.配置文件 application-pro.yml

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    dynamic:
      # 设置默认的数据源或者数据源组,默认值即为 master
      primary: master
      # 严格模式 匹配不到数据源则报错
      strict: true
      datasource:
		# 主库从库名字自定义
        # 主库
        master:
          driver-class-name: com.mysql.cj.jdbc.Driver
          username: xxx
          password: xxxxx
          url: jdbc:mysql://192.168.1.1:3306/database1?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=Asia/Shanghai
        # 从库1  
		slave:
          driver-class-name: com.mysql.cj.jdbc.Driver
          username: xxx
          password: xxxxx
          url: jdbc:mysql://192.168.1.2:3307/database2?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=Asia/Shanghai
        # 从库2
		slave2:
          driver-class-name: com.mysql.cj.jdbc.Driver
          username: xxx
          password: xxxxx
          url: jdbc:mysql://192.168.1.3:3308/database3?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=Asia/Shanghai		
      druid:
        enable: true
        max-active: 150
        min-idle: 50
        initial-size: 50
        max-wait: 60000
        time-between-eviction-runs-millis: 60000
        validation-query: select server_status()
        test-on-return: false
        test-while-idle: true
        test-on-borrow: false
        async-close-connection-enable: true
        async-init: true

3.对应mapper接口使用不同的数据源

import com.baomidou.dynamic.datasource.annotation.DS;

@Mapper
public class UserService {
 	// m默认使用名为 "master" 的数据源
    public void updateUser(User user) {
        // 创建用户
    }
    
    @DS("master") // 使用名为 "master" 的数据源
    public void createUser(User user) {
        // 创建用户
    }

    @DS("slave") // 使用名为 "slave" 的数据源
    public User getUserById(long id) {
        // 根据ID获取用户
        return null;
    }
	@DS("slave1") // 使用名为 "slave1" 的数据源
    public User getUserById(long id) {
        // 根据ID获取用户
        return null;
    }
    // 其他方法...
}

4.对应mapper接口使用相同的数据源

import com.baomidou.dynamic.datasource.annotation.DS;
// 使用名为 "master" 的数据源
@Mapper
@DS("master")
public class UserService {

 
    public void createUser(User user) {
        // 创建用户
    }

  
    public User getUserById(long id) {
        // 根据ID获取用户
        return null;
    }

    public User getUserById(long id) {
        // 根据ID获取用户
        return null;
    }
    // 其他方法...
}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中,我们可以使用多个数据源,但是默认情况下只能使用一个数据源。如果我们想要使用多个数据源,我们可以使用Dynamic DataSource Routing(动态数据源路由)来解决这个问题。Dynamic DataSource Routing可以根据当前线程的上下文信息来动态地切换数据源。 在使用Dynamic DataSource Routing之前,我们需要使用Spring Boot的AOP功能来拦截MyBatis的Mapper接口,并根据当前线程的上下文信息来动态地切换数据源。具体步骤如下: 1.添加依赖 ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>${dynamic.datasource.version}</version> </dependency> ``` 2.配置数据源 ```yaml spring: datasource: master: url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false username: root password: root driver-class-name: com.mysql.jdbc.Driver slave1: url: jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false username: root password: root driver-class-name: com.mysql.jdbc.Driver ``` 3.配置动态数据源 ```java @Configuration public class DataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource.master") public DataSource masterDataSource() { return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix = "spring.datasource.slave1") public DataSource slave1DataSource() { return DataSourceBuilder.create().build(); } @Bean public DynamicDataSource dynamicDataSource(@Qualifier("masterDataSource") DataSource masterDataSource, @Qualifier("slave1DataSource") DataSource slave1DataSource) { Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource); targetDataSources.put(DataSourceType.SLAVE1.name(), slave1DataSource); return new DynamicDataSource(masterDataSource, targetDataSources); } } ``` 4.配置AOP ```java @Aspect @Component public class DataSourceAspect { @Pointcut("@annotation(com.baomidou.dynamic.datasource.annotation.DS)") public void dsPointCut() { } @Before("dsPointCut()") public void beforeSwitchDS(JoinPoint point) { MethodSignature signature = (MethodSignature) point.getSignature(); DS annotation = signature.getMethod().getAnnotation(DS.class); if (annotation == null) { DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MASTER); } else { DynamicDataSourceContextHolder.setDataSourceType(annotation.value()); } } @After("dsPointCut()") public void afterSwitchDS(JoinPoint point) { DynamicDataSourceContextHolder.clearDataSourceType(); } } ``` 5.使用@DS注解来动态指定数据源 ```java @DS("slave1") public interface UserMapper { List<User> findAll(); } ``` 以上就是在Spring Boot配置多数据源的方法,通过Dynamic DataSource Routing来实现动态切换数据源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值