赞
踩
dynamic-datasource-spring-boot-starter 是一个基于springboot的快速集成多数据源的启动器。
其支持 Jdk 1.7+, SpringBoot 1.4.x 1.5.x 2.x.x。
在pom.xml文件中添加maven依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.6.0</version>
</dependency>
修改application.yml文件,添加数据源:
spring: datasource: dynamic: primary: master #设置默认的数据源或者数据源组,默认值即为master datasource: master: url: jdbc:mysql://xx.xx.xx.xx:3306/dynamic username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver slave_1: url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver slave_2: diver-class-name: oracle.jdbc.driver.OracleDriver url: jdbc:oracle:thin:@xx.x.x.xxx:1521/orcl username: ENC(5xRxUfgT71VlnqnNNyA==) password: ENC(qcs40ScFvIlfK6X8UvBKg==) #......省略 #以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2
@DS 可以注解在方法上或类上,同时存在就近原则:方法上注解 优先于类上注解。
如果没有@DS,就是默认数据源,即2.2中的“master”。
某个Mapper对应的表只在确定的一个库,建议直接注解在mapper上。
@Repository
@DS("slave_1")
public interface Test2Mapper extends BaseMapper {
HashMap testQuery(Map<String, Object> query);
void testUpdate(Map<String, Object> query);
}
注解在BLO的实现类的方法或类上,BLO主要是对业务的处理, 在复杂的场景涉及连续切换不同的数据库。
@Slf4j @Service @Resource @DS("slave_2") public class TestBLOImpl extends BLOImpl implements TestBLO { @Resource private TestMapper testMapper; @Resource private Test2Mapper test2Mapper; @Override public Map<String, Object> testQuery(Map<String, Object> map) throws Exception { HashMap result = new HashMap<>(); Map<String, Object> resultDB1 = testMapper.testQuery(map); Map<String, Object> resultDB2 = test2Mapper.testQuery(map); result.put("resultDB1",resultDB1); result.put("resultDB2",resultDB2); return result; } @DS("slave_1") @Override public Map<String, Object> testQuery2(Map<String, Object> map) throws Exception { return testMapper.testQuery(map); } @Override public Map<String, Object> testUpdate(Map<String, Object> map) { testMapper.testUpdate(map); return null; } }
修改类MybatisPlusConfig中的mybatisPlusInterceptor方法,将分页拦截器指定的数据库类型去掉,框架会根据数据库连接自动设置sql方言类型。
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
在最外层的方法添加 @DSTransactional,底下调用的各个类该切数据源就正常使用DS切换数据源即可。
@Service
public class TestBPOImpl extends BPOImpl implements TestBPO {
@Resource
TestBLO testBLO;
@Override
@DSTransactional
public Map<String, Object> testUpdate(Map<String, Object> map) {
return testBLO.testUpdate(map);
}
}
不能使用@Transactional进行事务控制,否则会导致@DS注解切换数据源失败。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。