事务@DS切换多数据源失效

我的代码案例
动态数据源 - 文档
AOP注解 - 文档

前言

在上面 我的代码案例 已经有了,这里复制一份

1
2
3
4
5
6
7
2026-01-21 15:58:23
多数据源,不使用事务问题
.
问题:在事务中,切换 @DS("doris") 不能切换数据源。
说明:我这里的 slave 并不是真正意思的从库,而是大数据的库,如果数据源切换不了,导致查询表不存在了。
.
解决:AOP 拦截 @DS("doris"),Propagation.NOT_SUPPORTED 不使用事务执行

工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.taopanfeng.springbootdynamicdatasource.aop;

import cn.hutool.core.lang.Opt;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.support.TransactionTemplate;

import static org.springframework.core.annotation.MergedAnnotations.SearchStrategy.TYPE_HIERARCHY;

@Aspect
@Component
public class DorisTransactionAspect {

@Autowired
private PlatformTransactionManager transactionManager;

@Around("execution(* *(..)) && (@within(com.baomidou.dynamic.datasource.annotation.DS) || @annotation(com.baomidou.dynamic.datasource.annotation.DS))")
public Object handleDorisTransaction(ProceedingJoinPoint joinPoint) throws Throwable {
Class<?> clazz = joinPoint.getTarget().getClass();
DS dsMethod = Opt.ofTry(() -> ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(DS.class)).get();
DS dsClass = Opt.ofTry(() -> clazz.getAnnotation(DS.class)).get();
String dsInterface = Opt.ofTry(() -> MergedAnnotations.from(clazz, TYPE_HIERARCHY).get(DS.class).getString("value")).get();

// 方法 > 类 > 接口
String dataSourceKey = null;
if (dsMethod != null) {
dataSourceKey = dsMethod.value();
} else if (dsClass != null) {
dataSourceKey = dsClass.value();
} else if (dsInterface != null) {
dataSourceKey = dsInterface;
}

// 拦截 @DS("doris")
if ("doris".equals(dataSourceKey)) {
// 使用编程式事务管理,设置NOT_SUPPORTED传播行为
TransactionTemplate template = new TransactionTemplate(transactionManager);
template.setPropagationBehavior(Propagation.NOT_SUPPORTED.value());

return template.execute(status -> {
try {
return joinPoint.proceed();
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
});
}

return joinPoint.proceed();
}
}