spring項(xiàng)目如何配置多數(shù)據(jù)源(已上生產(chǎn),親測有效)
更新時(shí)間:2023年12月29日 09:21:15 作者:陳賝
這篇文章主要介紹了spring項(xiàng)目如何配置多數(shù)據(jù)源(已上生產(chǎn),親測有效),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
方式一(推薦)
注解形式添加
引入依賴
<!-- dynamic-datasource 多數(shù)據(jù)源-->
<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:
# 設(shè)置默認(rèn)的數(shù)據(jù)源或者數(shù)據(jù)源組,默認(rèn)值即為 master
primary: master
# 嚴(yán)格模式 匹配不到數(shù)據(jù)源則報(bào)錯(cuò)
strict: true
datasource:
# 主庫數(shù)據(jù)源
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
# 從庫庫數(shù)據(jù)源
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
# 從庫庫數(shù)據(jù)源
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
修改配置文件,添加數(shù)據(jù)源配置
修改application.yaml
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
添加配置類

主數(shù)據(jù)源配置
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;
/**
* 主數(shù)據(jù)源配置
*
* @author 陳琛
* @date 2022/05/09
*/
@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);
}
}
次數(shù)據(jù)源配置
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;
/**
* 第二個(gè)數(shù)據(jù)源配置
*
* @author 陳琛
* @date 2022/05/09
*/
@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);
}
}
數(shù)據(jù)源分配

- 主數(shù)據(jù)源正常使用之前的mapper
- 次數(shù)據(jù)源使用之后新建的websiteMapper
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Caused by: java.io.IOException: DerInputStrea
這篇文章主要介紹了Caused by: java.io.IOException: DerInputStream.getLength(): lengthTag=111, too big,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-10-10
Java FileDescriptor總結(jié)_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
FileDescriptor 是“文件描述符”??梢员挥脕肀硎鹃_放文件、開放套接字等。接下來通過本文給大家分享Java FileDescriptor總結(jié),感興趣的朋友一起學(xué)習(xí)吧2017-05-05
Java回調(diào)函數(shù)與觀察者模式實(shí)例代碼
這篇文章主要介紹了Java回調(diào)函數(shù)與觀察者模式實(shí)例代碼,簡單介紹了使用觀察者模式的場景,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02

