SpringBoot+Mybatis+Druid多数据源切换

SpringBoot+Mybatis+Druid多数据源切换

本文介绍如何使用mybatis实现多数据源切换,并实现动态数据源的添加和删除

pom.xml文件



    4.0.0

    org.example
    test03-dynamic
    1.0-SNAPSHOT
    
        test04-dynamic-druid
    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.5.RELEASE
    
    

    
        1.8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.projectlombok
            lombok
        

        
            com.alibaba
            druid-spring-boot-starter
            1.2.9
        

        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.2.2
        
        
            mysql
            mysql-connector-java
            8.0.13
        
    

application.yml文件配置数据源相关信息

server:
  port: 8090
spring:
  datasource:
    db1:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/test_druid?useUnicode=true&useSSL=false&characterEncoding=utf8
      username: root
      password: 760171
    db2:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/test_mybatis?useUnicode=true&useSSL=false&characterEncoding=utf8
      username: root
      password: 760171

mybatis:
  mapperLocations: classpath:mybatis/mapper/*.xml
  typeAliasesPackage: example.domain

DataSourceConfig

数据源配置


import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {
    
    @Bean(name = "db1")
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public DataSource dataSource1() {
        return new DruidDataSource() ;
    }

    @Bean(name = "db2")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource dataSource2() {
        return new DruidDataSource();
    }

    @Bean("dynamicDataSource")
    @Primary
    public DataSource dynamicDataSource ( @Qualifier("db1") DataSource db1,@Qualifier("dbMap") DataSourceMap dbMap) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource() ;
        dynamicDataSource.setDefaultTargetDataSource(db1);
        dynamicDataSource.setTargetDataSources(dbMap.getDbMap());
        return dynamicDataSource ;
    }

    @Bean
    public PlatformTransactionManager transactionManager(@Qualifier("dynamicDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

自定义DynamicDataSource(继承自AbstractRoutingDataSource)


import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceUtil.getDB();
    }
}

DataSourceUtil(为保证多用户情况下切换数据源不受干扰,使用ThreadLocal保存数据源名)


public class DataSourceUtil {

    private static final ThreadLocal contextHolder = new ThreadLocal<>() ;

    /**
     * 设置数据源名
     * @param dbType
     */
    public static void setDB(String dbType) {
        contextHolder.set(dbType);
    }
    public static String getDB() {
        return contextHolder.get() ;
    }

    public static void clearDB() {
        contextHolder.remove();
    }


}

DataSourceMap(设置DataSourceMap,成员变量dbMap保存数据源信息,初始化时将配置文件的数据源db1和db2保存如dbMap中)
如需要动态添加数据源,只需要实现put和remove方法,对成员变量dbMap里面的数据源进行动态的添加和删除即可。


import lombok.Data;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Component("dbMap")
@Data
public class DataSourceMap  {
    private Map dbMap ;

    public DataSourceMap(@Qualifier("db1")DataSource db1, @Qualifier("db2")DataSource db2) {
        this.dbMap = new HashMap() ;
        this.dbMap.put("db1",db1) ;
        this.dbMap.put("db2",db2) ;
    }

    public Map getDbMap() {
        return dbMap;
    }

    public void setDbMap(Map dbMap) {
        this.dbMap = dbMap;
    }
}

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