91名师指路-头部
91名师指路

spring boot 使用dynamic-datasource-spring-boot-starter实现多数据源

由于某些原因,现在不支持支付宝支付,如需要购买源码请加博主微信进行购买,微信号:13248254750

一:引入pom

<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>4.1.2</version>
</dependency>

<dependency>
  <groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.15</version>
</dependency>


二:添加配置

server:
port: 9001

spring:
application:
name: mszl-log
datasource:
dynamic:
primary: master # 设置默认数据源
strict: true # 严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
master:
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
url: jdbc:p6spy:postgresql://192.168.10.100:5432/mszl?characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=GMT%2B8
username: postgres
password: pgP@$$w0rd
db0:
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
url: jdbc:p6spy:postgresql://192.168.10.200:5432/db0?characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=GMT%2B8
username: postgres
password: pgP@$$w0rd
db1:
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
url: jdbc:p6spy:postgresql://192.168.10.300:5432/db1?characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=GMT%2B8
username: postgres
password: pgP@$$w0rd


druid:
type: com.alibaba.druid.pool.DruidDataSource
max-active: 100 # 最大连接数
initial-size: 1 # 初始化大小
max-wait: 60000 # 获取连接等待超时时间
min-idle: 1 # 最小连接数
time-between-eviction-runs-millis: 60000 # 间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
min-evictable-idle-time-millis: 300000 # 一个连接在池中最小生存的时间,单位是毫秒
validation-query: select 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
pool-prepared-statements: true
max-open-prepared-statements: 50
max-pool-prepared-statement-per-connection-size: 20
connect-timeout: 60000 # 建立链接需要的时间,单位毫秒: 60s
socket-timeout: 60000 # 发送请求给数据库(建立链接后),数据库处理的最大时间, 单位毫秒: 60s

mybatis-plus:
type-aliases-package: com.mszl.entity # 所有Entity别名类所在包
mapper-locations:
- classpath:mapper/**/*.xml # mapper映射文件
configuration:
map-underscore-to-camel-case: true # 设置实体类中的属性驼峰转换为下划线(和config-location不能并存)
call-setters-on-nulls: true # 解决map中返回的字段为空时不显示key的问题


三:controller

@PostMapping("/insert")
public ReturnMsgUtils insertDataAssetsLog(@RequestBody @Validated DataAssetsLogVO dv){
ReturnMsgUtils result=sysApiLogsService.insertDataAssetsLog(dv);
return result;
}


四:service

public interface SysApiLogsService extends IService<SysApiLogs> {

ReturnMsgUtils insertDataAssetsLog(DataAssetsLogVO dv);

}


五:serviceImpl

@DSTransactional(rollbackFor = Exception.class) // 注意如果这里使用@Transactional会导致数据源切换失败
@Override
public ReturnMsgUtils insertDataAssetsLog(DataAssetsLogVO dv) {
SysApiLogs sl=new SysApiLogs();
sl.setId(IdUtil.getSnowflake(1, 1).nextId());
sl.setSourceSys(dv.getSourceSys());
sl.setTargetSys(dv.getTargetSys());
sl.setRequestParams(dv.getRequestParams());
sl.setRequestMethod(dv.getRequestMethod());
sl.setRequestUrl(dv.getRequestUrl());
sl.setStartDate(DateUtils.strConvertToLocalDateTime(dv.getStartDate()));
sl.setEndDate(DateUtils.strConvertToLocalDateTime(dv.getStartDate()));
sl.setCreateTime(LocalDateTime.now());

int add=sysApiLogsMapper.insertSysApiLogs(sl);
if(add==0){
throw new BusinessException(BusinessUtils.CODE_201, BusinessUtils.BUSINESS_MSG_202);
}

int edit=empMapper.updateEmp(sl);
if(edit==0){
throw new BusinessException(BusinessUtils.CODE_201, BusinessUtils.BUSINESS_MSG_203);
}

ReturnMsgUtils result=ReturnMsgUtils.success();
return result;
}


注意:

如果存在多个数据源切换使用@Transactional(rollbackFor = Exception.class)会导致数据源切换失败,例如:我们同时使用了主数据源和子数据源,我们切换到子数据源执行sql时,会到主数据源中去找这张表,肯定是找不到的,原因:Spring 开启事务后会维护一个 ConnectionHolder,保证在整个事务下,都是用同一个数据库连接。也就是说:使用了 @Transactional,Spring 会保证整个事务下都复用同一个 connection。


六:dao

@Component
public interface SysApiLogsMapper extends BaseMapper<SysApiLogs> {

@DS("db0")
int insertSysApiLogs(SysApiLogs sl);

}


备注:
1)默认为master数据库,如果要用slave库,在dao层的类或方法上加上 @DS("slave") 即可,如果方法和类上都加上了@DS("slave") 则方法优先于类注解

2)@DSTransactional用于多数据源事务回滚



2023-10-17 18:06:36     阅读(323)

名师出品,必属精品    https://www.91mszl.com

联系博主    
用户登录遮罩层
x

账号登录

91名师指路-底部