1、pom.xml
<!-- https://mvnrepository.com/artifact/com.baomidou/dynamic-datasource-spring-boot-starter基于springboot的快速集成多数据源 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
2、配置文件
spring.datasource.dynamic.primary=master
spring.datasource.dynamic.datasource.master.username=root
spring.datasource.dynamic.datasource.master.password=root
spring.datasource.dynamic.datasource.master.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.dynamic.datasource.master.url=jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=UTF-8&useSSL=true
spring.datasource.dynamic.datasource.slave_1.username=root
spring.datasource.dynamic.datasource.slave_1.password=root
spring.datasource.dynamic.datasource.slave_1.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.dynamic.datasource.slave_1.url=jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=UTF-8&useSSL=true
3、使用不同数据源
注解 | 结果 |
---|---|
无 | 默认数据源master |
@DS("slave_1") | slave_1某个库的名称 |
@Service
public class AreaPressServiceImpl extends BaseServiceImpl<AreaPressMapper, AreaPressEntity> implements IAreaPressService {
@Override
@DS("slave_1")
public AreaPressEntity selectByIdTestDB(Integer id) {
return baseMapper.selectById( id);
}
}
二、多数据源事务回滚
注:需使用上面多数据源
@DSTransactional注解原理-CSDN博客
1、代码
控制器方法
@ApiOperation(value="新增数据", nickname="新增数据")
@GetMapping(value = "insertData", produces = { "application/json; charset=utf-8" })
public String insert(HttpServletRequest request, @ApiParam(name="id", value="主键", required=false)Integer id) {
try {
int rows = transactionService.insertData(id);
if(rows>0){
return buildSuccessResult("新增数据成功",rows);
}
} catch (RuntimeException e) {
logger.error(e.getMessage());
}
return buildFailedResult("新增数据失败",null);
}
具体方法
@Override
@DSTransactional
public int insertData(Integer id) {
BookEntity bookEntity =new BookEntity();
bookEntity.setOnlineBookId(1);
bookEntity.setBookName("dsds");
bookEntity.setSourceType(1);
bookEntity.setStatus(1);
bookService.insert(bookEntity);
SysConfig sysConfig = new SysConfig();
sysConfig.setConfigKey("sdsd");
sysConfigService.insertConfig(sysConfig);
int i = 1;
//如果为1,直接回滚
if(id==1){
i=0;
i = 1 / 0;
}
return i;
}
实现类都添加数据库注解
@DS("slave")
public class BookServiceImpl
@DS("master")
public class SysConfigServiceImpl
2、