方法1:继承AbstractRoutingDataSource
application-dev.yaml添加数据源配置文件
spring:
datasource:
remote_local_test1:
username: root
password: root
driver-class-name: org.mariadb.jdbc.Driver
url: jdbc:mariadb://192.192.192.192:3306/local_test1?useUnicode=true&characterEncoding=UTF-8
remote_local_test2:
username: root
password: root
driver-class-name: org.mariadb.jdbc.Driver
url: jdbc:mariadb://192.192.192.192:3306/local_test2?useUnicode=true&characterEncoding=UTF-8
DynamicDataSourceConfig数据源配置类
@Configuration
public class DynamicDataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.remote_local_test1")
public DataSource firstDataSource(){
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.remote_local_test2")
public DataSource secondDataSource(){
return DruidDataSourceBuilder.create().build();
}
@Bean
@Primary
public DynamicDataSource dataSource(DataSource firstDataSource, DataSource secondDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>(5);
targetDataSources.put(DataSourceNames.FIRST, firstDataSource);
targetDataSources.put(DataSourceNames.SECOND, secondDataSource);
return new DynamicDataSource(firstDataSource, targetDataSources);
}
}
继承AbstractRoutingDataSource用于切换数据源
public class DynamicDataSource extends AbstractRoutingDataSource {
/**
* ThreadLocal 用于提供线程局部变量,在多线程环境可以保证各个线程里的变量独立于其它线程里的变量。
* 也就是说 ThreadLocal 可以为每个线程创建一个【单独的变量副本】,相当于线程的 private static 类型变量。
*/
private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
/**
* 决定使用哪个数据源之前需要把多个数据源的信息以及默认数据源信息配置好
*
* @param defaultTargetDataSource 默认数据源
* @param targetDataSources 目标数据源
*/
public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
super.setDefaultTargetDataSource(defaultTargetDataSource);
super.setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
return getDataSource();
}
public static void setDataSource(String dataSource) {
CONTEXT_HOLDER.set(dataSource);
}
public static String getDataSource() {
return CONTEXT_HOLDER.get();
}
public static void clearDataSource() {
CONTEXT_HOLDER.remove();
}
}
自定义注解CurDataSource,在方法或者类上标注
@Target({ElementType.METHOD,ElementType.TYPE})
//保留方式
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CurDataSource {
String name() default "";
}
枚举类DataSourceNames指定数据源名称
public interface DataSourceNames {
String FIRST = "first";
String SECOND = "second";
}
切面类DataSourceAspect用于获取标注了自定义注解的数据源的值
/**
* 多数据源,切面处理类
*
*/
@Slf4j
@Aspect
@Component
public class DataSourceAspect implements Ordered {
@Pointcut("@annotation(com.demo.other.CurDataSource)")
//切点表达式
public void dataSourcePointCut() {
}
@Around("dataSourcePointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
CurDataSource ds = method.getAnnotation(CurDataSource.class);
if (ds == null) {
DynamicDataSource.setDataSource(DataSourceNames.FIRST);
log.debug("set datasource is " + DataSourceNames.FIRST);
} else {
DynamicDataSource.setDataSource(ds.name());
log.debug("set datasource is " + ds.name());
}
try {
return point.proceed();
} finally {
DynamicDataSource.clearDataSource();
log.debug("clean datasource");
}
}
@Override
public int getOrder() {
return 1;
}
}
定义不同数据源的mapper
//数据源1的mapper
@Mapper
public interface User1Mapper {
@Select("select * from emp")
List<User> getAllUsers();
}
//数据源2的mapper
@Mapper
public interface User2Mapper {
@Select("select * from emp")
List<User> getAllUsers();
}
Service类中方法或者类上添加自定义数据源注解
@Service
public class SysUserServiceImpl implements SysUserService {
@Autowired
private User1Mapper user1Mapper;
@Autowired
private User2Mapper user2Mapper;
//第一个数据源可以不标注,默认就是第一个数据源
@Override
public List<User> findUserByFirstDb() {
List<User> allUsers = user1Mapper.getAllUsers();
return allUsers;
}
@CurDataSource(name = DataSourceNames.SECOND)
@Override
public List<User> findUserBySecondDb() {
List<User> allUsers = user2Mapper.getAllUsers();
return allUsers;
}
}
controller类
@Slf4j
@RestController
@RequestMapping("/dynamic")
public class UserController {
@Autowired
private SysUserService sysUserService;
@RequestMapping("/data")
private List<User> getUserData(){
List<User> userList = new ArrayList<>();
List<User> userByFirstDb = sysUserService.findUserByFirstDb();
log.info("第一个数据库的User数据:" + userByFirstDb);
List<User> userBySecondDb = sysUserService.findUserBySecondDb();
log.info("第二个数据库的User数据:" + userBySecondDb);
userList.addAll(userByFirstDb);
userList.addAll(userBySecondDb);
return userList;
}
}
启动类中排除默认DataSourceAutoConfiguration,引入自定义数据源DynamicDataSourceConfig
@MapperScan("com.demo.mapper")
@Import({DynamicDataSourceConfig.class})
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
方法2:@DS、@DSTransactional注解
pom文件,添加dynamic-datasource的依赖
<!--添加dynamic-datasource的依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
application-dev.yaml引入数据源,设置主数据源
spring:
datasource:
hikari:
minimum-idle: 4
maximum-pool-size: 16
connection-timeout: 10000
idle-timeout: 30000
connection-init-sql: set names utf8mb4
dynamic:
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
primary: bigData # 设置默认的数据源或者数据源组,默认值为master
datasource:
bigData:
username: root
password: root
driver-class-name: org.mariadb.jdbc.Driver
url: jdbc:mariadb://192.192.192.192:3306/bigData?useUnicode=true&characterEncoding=UTF-8
local_test:
username: root
password: root
driver-class-name: org.mariadb.jdbc.Driver
url: jdbc:mariadb://192.192.192.192:3306/local_test?useUnicode=true&characterEncoding=UTF-8
mapper接口或方法上添加@DS注解指定数据源
@Mapper
public interface UserMapper {
@DS("bigData")
@Insert("insert into departments(`dept_no`,`dept_name`) values(#{dept_no},#{dept_name})")
void saveDept(Deparment deparment);
@DS("local_test")
@Insert("insert into emp(`name`) values(#{name})")
void saveEmp(Emp emp);
}
service类方法上添加@DSTransactional注解,管理事务,模拟异常测试事务回滚
@Service
public class TestServiceImpl implements TestService {
@Autowired
private UserMapper userMapper;
@DSTransactional
@Override
public void t1() {
Deparment deparment = new Deparment();
deparment.setDept_name("zs-tr1");
deparment.setDept_no("007");
userMapper.saveDept(deparment);
Emp e2 = new Emp();
e2.setName("zs-tr2");
userMapper.saveEmp(e2);
//模拟异常,测试事务回滚
int a = 1/0;
}
}
controller调用service
@Slf4j
@RestController
@RequestMapping("/dynamic")
public class TestController {
@Autowired
private TestService testService;
@RequestMapping("/data")
public int getUserData(){
testService.t1();
return 1;
}
}
启动类中排除默认DataSourceAutoConfiguration
@MapperScan("com.demo.mapper")
//如果不排除 DataSourceAutoConfiguration,
//Spring Boot将尝试根据默认配置创建单个数据源。这与显式定义多数据源的意图相冲突
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}