1. 参考
https://blog.csdn.net/qq_51986979/article/details/134509199
https://gitcode.csdn.net/65e843bc1a836825ed78c2a8.html
https://blog.csdn.net/LSW1737554365/article/details/134179970
pom.xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
yaml
# 数据源1
spring.datasource.dynamic.primary = datasource1
spring.datasource.dynamic.datasource.xx.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.dynamic.datasource.xx.url = jdbc:mysql://XX:3306/xx?useUnicode=true&characterEncoding=utf8¤tSchema=public&useSSL=false
spring.datasource.dynamic.datasource.xx.username = XX
spring.datasource.dynamic.datasource.xx.password = XX
# 数据源2
spring.datasource.dynamic.datasource.techless.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.dynamic.datasource.techless.url = jdbc:mysql://XX:3306/db2?useUnicode=true&characterEncoding=utf8¤tSchema=public&useSSL=false
spring.datasource.dynamic.datasource.db2.username = XX
spring.datasource.dynamic.datasource.db2.password = XX
默认使用主数据源,需要切换其他数据源使用 注解:@DS(“db2”)
- @DS 可以注解在方法上或类上,同时存在就近原则 方法上注解 优先于 类上注解。
- 切换数据源 @DS 可以注解在对应 mapper 接口、service接口和实现类上,当注解到测试类或测试方法上时会失效
@Slf4j
@Service
@Primary
public class GitlabServiceImpl extends GitlabBaseServiceImpl {
}
package com.XX.xx.service.impl;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xx.xx.orm.domain.IdmUser;
import com.xx.xx.orm.mapper.IdmUserMapper;
import com.xx.xx.service.IdmUserService;
import java.util.List;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/**
* <p>
* IDM服务实现类
* </p>
*
* @since 2022-05-11
*/
@DS("db2")
@Service
public class IdmUserServiceImpl extends ServiceImpl<IdmUserMapper, IdmUser> implements IdmUserService {
@Override
@Cacheable(cacheNames = "idmUserByCodeCache", key = "#code")
public IdmUser getByCode(String code) {
EntityWrapper<IdmUser> queryWrapper = new EntityWrapper();
queryWrapper.eq("username", code);
return selectOne(queryWrapper);
}
}