动态数据源

Pig 的多数据配置,是基于 dynamic-datasource-spring-boot-starter 实现,理论上支持此组件的全部功能。

如何使用

1. 业务服务引入动态数据源服务

<dependency>
  <groupId>com.pig4cloud</groupId>
  <artifactId>pig-common-datasource</artifactId>
</dependency>

2. 配置数据源信息来源(JDBC 配置)

## 默认查询本服务数据源 ` gen_datasource_conf`,可参考 `pig_codegen` 模块
spring:
  datasource:
    druid:
      query-ds-sql: 'select * from gen_datasource_conf where del_flag = 0'

3. 开启动态数据源

@EnableDynamicDataSource
public class App {
   public static void main(String[] args) {
      SpringApplication.run(App.class, args);
   }
}

4. 使用动态数据源查询

Mapper 层 @DS("#last") 固定写法,最后一个参数为指定数据源(必须有)

@Mapper
public interface DemoMapper extends BaseMapper<Demo> {
   @DS("#last")
   Map selectDs(String dsName);
}

Service 层调用

@Service
public class DemoServiceImpl extends ServiceImpl<DemoMapper, Demo> implements DemoService {
   @Override
   public Object getByDs(Integer id) {
      // 此处 dsName 为以上 gen_datasource_conf 加载数据源 name 字段
      return baseMapper.selectDs("pigxx_core");
   }
}

扩展使用

可以参考官方文档:动态参数解析数据源

@DS("#session.tenantName")
public List selectSpelBySession() {
   return userMapper.selectUsers();
}

获取支持

遇到问题?

如果您在使用过程中遇到任何问题、有功能建议或需求,请点击此处前往 Gitee 仓库提交 Issue。