🌸 方式一(推荐): 🌸
🌸 注解形式添加
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
dynamic:
primary: master
strict: true
datasource:
master:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: xxxxx
url: jdbc:mysql://127.0.0.1:3306/ifssc-iot?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=Asia/Shanghai
slave:
driver-class-name: com.taosdata.jdbc.rs.RestfulDriver
url: jdbc:TAOS-RS://127.0.0.1:6041/power?charset=UTF-8&locale=en_US.UTF-8&timezone=UTC-8
username: root
password: xxxxx
slave2:
driver-class-name: com.taosdata.jdbc.rs.RestfulDriver
url: jdbc:TAOS-RS://127.0.0.1:6041/power?charset=UTF-8&locale=en_US.UTF-8&timezone=UTC-8
username: root
password: xxxxx
druid:
enable: true
max-active: 50
min-idle: 50
initial-size: 50
max-wait: 60000
time-between-eviction-runs-millis: 60000
validation-query: select server_status()
test-on-return: false
test-while-idle: true
test-on-borrow: false
async-close-connection-enable: true
async-init: true
- 使用 直接加在使用的方法上即可
- @Slave
- @DS(“slave2”)
- @DS(“xxx”)
@Slave
public ResultVO test() {
LambdaQueryWrapper<Temperature> lqw = new QueryWrapper<Temperature>().lambda()
.eq(Temperature::getLocation, "杭州")
.last("limit 10");
List<Temperature> temperatureList = temperatureMapper.selectList(lqw);
return ResultVO.success(temperatureList);
}
@Slave2
public ResultVO test() {
LambdaQueryWrapper<Temperature> lqw = new QueryWrapper<Temperature>().lambda()
.eq(Temperature::getLocation, "杭州")
.last("limit 10");
List<Temperature> temperatureList = temperatureMapper.selectList(lqw);
return ResultVO.success(temperatureList);
}
方式二:分开配置mapper,不影响之前的mapper
修改配置文件,添加数据源配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
db1:
enable: true
driver-class-name: com.mysql.cj.jdbc.Driver
max-active: 100
min-idle: 100
initial-size: 100
max-wait: 60000
time-between-eviction-runs-millis: 60000
validation-query: SELECT 1 FROM DUAL
jdbc-url: jdbc:mysql://***:3306/***2?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=Asia/Shanghai
username: root
password: ***
test-on-return: false
test-while-idle: true
test-on-borrow: false
async-close-connection-enable: true
async-init: true
use-unfair-lock: true
db2:
enable: true
driver-class-name: com.mysql.cj.jdbc.Driver
max-active: 100
min-idle: 100
initial-size: 100
max-wait: 60000
time-between-eviction-runs-millis: 60000
validation-query: SELECT 1 FROM DUAL
jdbc-url: jdbc:mysql://***:3306/***1?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=Asia/Shanghai
username: root
password: ***
test-on-return: false
test-while-idle: true
test-on-borrow: false
async-close-connection-enable: true
async-init: true
use-unfair-lock: true
#mybatis
mybatis-plus:
type-aliases-package: com.***.cloud.common.entity # 所有Entity别名类所在包
mapper-locations: classpath:mapper/**/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 配置打印日志
call-setters-on-nulls: true
cache-enabled: false
- 添加配置类
![在这里插入图片描述](https://img-blog.csdnimg.cn/6de80336c8bf41f3a5ec0240b12f8d4a.png)
- 主数据源配置
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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.context.annotation.Scope;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.annotation.Resource;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = {"com.xxx.cloud.platform.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory")
public class PrimaryDataSourceConfig {
@Resource
private MybatisPlusInterceptor mybatisPlusInterceptor;
@Value("${mybatis-plus.mapper-locations}")
private String locationPattern;
@Value("${mybatis-plus.type-aliases-package}")
private String typeAliasesPackage;
@Bean
@Scope(value = "prototype")
@ConfigurationProperties(prefix = "mybatis-plus.configuration")
public MybatisConfiguration getCfg() {
return new MybatisConfiguration();
}
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource.druid.db1")
@Primary
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "sqlSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setPlugins(mybatisPlusInterceptor);
bean.setConfiguration(getCfg());
bean.setTypeAliasesPackage(typeAliasesPackage);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(locationPattern));
return bean.getObject();
}
@Bean(name = "transactionManager")
@Primary
public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "sqlSessionTemplate")
@Primary
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.annotation.Resource;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = {"com.xxx.cloud.platform.websiteMapper"}, sqlSessionFactoryRef = "sqlSessionFactory2")
public class SecondDataSourceConfig {
@Resource
private MybatisPlusInterceptor mybatisPlusInterceptor;
@Value("${mybatis-plus.mapper-locations}")
private String locationPattern;
@Value("${mybatis-plus.type-aliases-package}")
private String typeAliasesPackage;
@Resource
private MybatisConfiguration mybatisConfiguration;
@Bean(name = "dataSource2")
@ConfigurationProperties(prefix = "spring.datasource.druid.db2")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "sqlSessionFactory2")
public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource2") DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setPlugins(mybatisPlusInterceptor);
bean.setConfiguration(mybatisConfiguration);
bean.setTypeAliasesPackage(typeAliasesPackage);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(locationPattern));
return bean.getObject();
}
@Bean(name = "transactionManager2")
public DataSourceTransactionManager transactionManager(@Qualifier("dataSource2") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "sqlSessionTemplate2")
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory2") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
数据源分配
![在这里插入图片描述](https://img-blog.csdnimg.cn/e5cf66538cd84f9bb54e453a4cfc4b8c.png)
- 主数据源正常使用之前的mapper
- 次数据源使用之后新建的websiteMapper