手动实现MySql动态数据源配置

MySql动态数据源配置实践

环境

Spring Boot项目作为主体框架,使用Mybatis-Plus作为操作数据库框架。

思路

  • 通过配置文件配置数据源,Spring在启动的时候自动将配置好的多数据源加载到容器。
  • 使用Spring-Boot-starter-JDBC依赖里面的AbstractRoutingDataSource类进行实现。
  • 编写配置类,将自动注入的数据源设置到AbstractRoutingDataSource类的TargetDataSources。
  • 实现AbstractRoutingDataSource类的determineCurrentLookupKey(),使用ThreadLocal进行数据库切换。

特点

  • 可以根据传入参数不同,进行数据源切换。

代码

pom依赖

 <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
        dependency>
    dependencies>

配置

server:
  port: 8888

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
#    第一个数据源
    datasource1:
      url: jdbc:mysql://192.168.244.100:3306/study1?serverTimezone=UTC
      username: root
      password: root
      initial-size: 1
      min-idle: 1
      max-active: 20
      test-on-borrow: true
      driver-class-name: com.mysql.cj.jdbc.Driver
#    第二个数据源
    datasource2:
      url: jdbc:mysql://192.168.244.100:3306/study2?serverTimezone=UTC
      username: root
      password: root
      initial-size: 1
      min-idle: 1
      max-active: 20
      test-on-borrow: true
      driver-class-name: com.mysql.cj.jdbc.Driver

核心实现

数据源加载配置
@Configuration
public class LoadDataSourceConfig {

    @Bean(name = "dataSource1")
    @ConfigurationProperties(prefix = "spring.datasource.datasource1")
    public DataSource dataSource1(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "dataSource2")
    @ConfigurationProperties(prefix = "spring.datasource.datasource2")
    public DataSource dataSource2(){
        return DruidDataSourceBuilder.create().build();
    }
}

动态数据源配置
@Component("dynamicDataSource")
@Primary
public class DynamicDataSourceConfig extends AbstractRoutingDataSource {

    public static ThreadLocal<String> dataBaseName = new ThreadLocal<>();

    @Resource(name = "dataSource1")
    DataSource dataSource1;

    @Resource(name = "dataSource2")
    DataSource dataSource2;


    @Override
    protected Object determineCurrentLookupKey() {
        return dataBaseName.get();
    }

    @Override
    public void afterPropertiesSet() {
        HashMap<Object, Object> map = new HashMap<>();
        map.put("write",dataSource1);
        map.put("read",dataSource2);
        // 设置数据源
        super.setTargetDataSources(map);
        // 设置默认库
        super.setDefaultTargetDataSource(dataSource1);
        super.afterPropertiesSet();
    }
}

使用

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentMapper studentMapper;


    @RequestMapping(value = "/save",method = RequestMethod.GET)
    public String saveStudent(@RequestParam(name= "name") String name,@RequestParam(name= "sex") String sex,@RequestParam(name= "ds",defaultValue = "write") String ds){
        DynamicDataSourceConfig.dataBaseName.set(ds);
        Student student = new Student();
        student.setName(name);
        student.setSex(sex);
        student.setCreateTime(LocalDateTime.now());
        studentMapper.insert(student);
        return "success!!";
    }

    @RequestMapping(value = "/get",method = RequestMethod.GET)
    @ResponseBody
    public Student query(@RequestParam(name = "id") String id,@RequestParam(name= "ds",defaultValue = "read") String ds){
        DynamicDataSourceConfig.dataBaseName.set(ds);
        return studentMapper.selectById(id);
    }

}

源码地址:https://gitee.com/sihehe/spring-mysql.git

你可能感兴趣的:(mysql,mysql,mybatis,java,spring,boot)