以动态多数据源为例
文件目录
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.oumiga.datasource</groupId>
<artifactId>spring-boot-starter-dynamic-datasource2</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<mybatis-version>3.5.7</mybatis-version>
<druid-version>1.2.6</druid-version>
<mybatis-spring>2.0.6</mybatis-spring>
<mysql.version>8.0.11</mysql.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<scope>compile</scope>
<version>2.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis-version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid-version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
MasterDateSourceProperties //主数据源参数
package com.oumiga.datasource.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "spring.datasource.master")
public class MasterDateSourceProperties {
private String driverClassName;
private String url;
private String username;
private String password;
private Integer maxActive = 1000;
private Integer maxWait = 500;
private Integer minIdle = 110;
private Integer initialSize = 100;
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getMaxActive() {
return maxActive;
}
public void setMaxActive(Integer maxActive) {
this.maxActive = maxActive;
}
public Integer getMaxWait() {
return maxWait;
}
public void setMaxWait(Integer maxWait) {
this.maxWait = maxWait;
}
public Integer getMinIdle() {
return minIdle;
}
public void setMinIdle(Integer minIdle) {
this.minIdle = minIdle;
}
public Integer getInitialSize() {
return initialSize;
}
public void setInitialSize(Integer initialSize) {
this.initialSize = initialSize;
}
}
SlaveDateSourceProperties //从数据源参数
package com.oumiga.datasource.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "spring.datasource.slave")
public class SlaveDateSourceProperties {
private String driverClassName;
private String url;
private String username;
private String password;
private Integer maxActive = 1000;
private Integer maxWait = 500;
private Integer minIdle = 110;
private Integer initialSize = 100;
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getMaxActive() {
return maxActive;
}
public void setMaxActive(Integer maxActive) {
this.maxActive = maxActive;
}
public Integer getMaxWait() {
return maxWait;
}
public void setMaxWait(Integer maxWait) {
this.maxWait = maxWait;
}
public Integer getMinIdle() {
return minIdle;
}
public void setMinIdle(Integer minIdle) {
this.minIdle = minIdle;
}
public Integer getInitialSize() {
return initialSize;
}
public void setInitialSize(Integer initialSize) {
this.initialSize = initialSize;
}
}
数据库切换枚举类
package com.oumiga.datasource.constant;
public enum DataSourceTypeEnum {
MASTER,
SLAVE
}
DataSourceContextHolder
package com.oumiga.datasource.config;
import com.oumiga.datasource.constant.DataSourceTypeEnum;
public class DataSourceContextHolder{
private static final ThreadLocal<DataSourceTypeEnum> contextHolder = new ThreadLocal<>();
public static void addDataSource(DataSourceTypeEnum dataSourceTypeEnum){
contextHolder.set(dataSourceTypeEnum);
}
public static DataSourceTypeEnum getDataSource(){
return contextHolder.get();
}
public static void removeDataSource(){
contextHolder.remove();
}
}
DynamicDataSource
package com.oumiga.datasource.config;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSource();
}
}
DatesourceConfig
package com.oumiga.datasource.config;
import com.alibaba.druid.DbType;
import com.alibaba.druid.pool.DruidDataSource;
import com.oumiga.datasource.constant.DataSourceTypeEnum;
import com.oumiga.datasource.properties.MasterDateSourceProperties;
import com.oumiga.datasource.properties.SlaveDateSourceProperties;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableConfigurationProperties({MasterDateSourceProperties.class,SlaveDateSourceProperties.class})
public class DatesourceConfig {
@Resource
private MasterDateSourceProperties masterDateSourceProperties;
@Resource
private SlaveDateSourceProperties slaveDateSourceProperties;
@Bean(name = "masterDruidDataSource")
@Primary
public DruidDataSource masterDruidDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setMaxActive(masterDateSourceProperties.getMaxActive());
dataSource.setMaxWait(masterDateSourceProperties.getMaxWait());
dataSource.setMinIdle(masterDateSourceProperties.getMinIdle());
dataSource.setInitialSize(masterDateSourceProperties.getInitialSize());
dataSource.setDriverClassName(masterDateSourceProperties.getDriverClassName());
dataSource.setDbType(DbType.mysql);
dataSource.setUrl(masterDateSourceProperties.getUrl());
dataSource.setUsername(masterDateSourceProperties.getUsername());
dataSource.setPassword(masterDateSourceProperties.getPassword());
return dataSource;
}
@Bean(name = "slaveDruidDataSource")
public DruidDataSource slaveDruidDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setMaxActive(slaveDateSourceProperties.getMaxActive());
dataSource.setMaxWait(slaveDateSourceProperties.getMaxWait());
dataSource.setMinIdle(slaveDateSourceProperties.getMinIdle());
dataSource.setInitialSize(slaveDateSourceProperties.getInitialSize());
dataSource.setDriverClassName(slaveDateSourceProperties.getDriverClassName());
dataSource.setDbType(DbType.mysql);
dataSource.setUrl(slaveDateSourceProperties.getUrl());
dataSource.setUsername(slaveDateSourceProperties.getUsername());
dataSource.setPassword(slaveDateSourceProperties.getPassword());
return dataSource;
}
@Bean(name = "dynamicDataSource")
public DynamicDataSource dataSource(@Qualifier("slaveDruidDataSource")DruidDataSource slaveDataSource,@Qualifier("masterDruidDataSource") DruidDataSource masterDruidDataSource){
Map<Object,Object> targetDataSource = new HashMap<>();
targetDataSource.put(DataSourceTypeEnum.MASTER,masterDruidDataSource);
targetDataSource.put(DataSourceTypeEnum.SLAVE,slaveDataSource);
DynamicDataSource dynamicDataSource = new DynamicDataSource();
dynamicDataSource.setTargetDataSources(targetDataSource);
dynamicDataSource.setDefaultTargetDataSource(masterDruidDataSource);
return dynamicDataSource;
}
@Bean(name = "SqlSessionFactory")
public SqlSessionFactory test1SqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dynamicDataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath*:*Mapper/*.xml"));
return bean.getObject();
}
}
spring.factories文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.oumiga.datasource.config.DatesourceConfig
application.yml
spring:
datasource:
master:
##我默认使用了druid连接池
max-wait: 500
min-idle: 110
max-active: 1000
initial-size: 100
#####################
basePackages: com.oumiga.local.xianDao
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.91.110:3306/test1?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8&useOldAliasMetadataBehavior=true&allowPublicKeyRetrieval=true
username: root
password: 123456
slave:
max-wait: 500
min-idle: 110
max-active: 1000
initial-size: 100
basePackages: com.oumiga.local.wlmqDao
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.91.110:3306/test2?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8&useOldAliasMetadataBehavior=true&allowPublicKeyRetrieval=true
username: root
password: 123456
在项目中引入jar包,还需要引入一下mybatis的相关jar包
<dependency>
<groupId>com.oumiga.datasource</groupId>
<artifactId>spring-boot-starter-dynamic-datasource2</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
使用方法
//默认使用的master数据源,此处不用切换可直接使用
masterDao.getUser();
DataSourceContextHolder.addDataSource(DataSourceTypeEnum.SLAVE);
slaveDao.getRole();
DataSourceContextHolder.removeDataSource();