document.write("");

springboot mybatis-plus 多数据源 & 根据接口入参动态切换DB

直接看官方文档,很详细,地址在最下方

1. 引入依赖

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>4.3.1</version>
        </dependency>

2. 配置数据源

spring:
  datasource:
    dynamic:
      primary: master
      strict: false
      datasource:
        master:
          url: jdbc:mysql://xx.xx.xx.xx:3306/dynamic
          username: root
          password: 123456
          driver-class-name: com.mysql.jdbc.Driver
        slave_1:
          url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic
          username: root
          password: 123456
          driver-class-name: com.mysql.jdbc.Driver
        slave_2:
          url: ENC(xxxxx)
          username: ENC(xxxxx)
          password: ENC(xxxxx)
          driver-class-name: com.mysql.jdbc.Driver

3. 注解切换DB

@Service
@DS("slave")
public class UserServiceImpl implements UserService {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  @Override
  @DS("slave_1")
  public List selectByCondition() {
    return jdbcTemplate.queryForList("select * from user where age >10");
  }
}

SpringBoot接口需要动态数据源切换,可以使用入参(以下为示例接口,需自行调整,比如SQL安全校验等等

Get方式-动态传参dataSource,用于动态切换DS注解的值

    /**
     * 动态切换DB接口
     *
     * @return 动态切换DB接口
     */
    @ApiOperation(value = "动态切换DB接口", notes="传参dataSource用于切换数据源,传参Sql用于查询")
    @GetMapping("/test")
    @DS("#dataSource")
    public ApiResult cust(@RequestParam String dataSource, @RequestParam String sql) throws Exception {
        return xxxSQLService.exc(sql);
    }

自定义查询SQL的Service

@Slf4j
@Service
public class XXXSQLService  {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public ApiResult exc(String sql) throws Exception {
        // 执行自定义SQL
        try {
            List<Map<String, Object>> datas = jdbcTemplate.queryForList(sql);
            return ApiResult.ok(datas.size() > 10 ? datas.subList(0, 10) : datas);
        } catch (Exception e) {
            return ApiResult.fail(e.getMessage());
        }
    }

}

Post方式-指定 入参的#condition.dataSource为DS注解的值

    /**
     * 动态切换DB接口(Post)
     *
     * @return 动态切换DB接口
     */
    @ApiOperation(value = "动态切换DB接口(Post)", notes="(表单传参)传参dataSource用于切换数据源,传参Sql用于查询")
    @PostMapping("/test")
    @DS("#condition.dataSource")
    public ApiResult test1(@RequestBody XXXCondition condition) throws Exception {
        return customSQLService.exc(condition.getSql());
    }
@Data
public class XXXCondition {
    private String sql;
    private String dataSource;
}

 

文档地址:

https://baomidou.com/guides/dynamic-datasource/

 

posted @ 2025-08-28 16:39  人间春风意  阅读(32)  评论(0)    收藏  举报