Skip to content

Commit 2aca778

Browse files
committed
feat: 添加动态数据源切换 AOP 类
1 parent f7a7774 commit 2aca778

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package top.cadecode.common.datasource;
2+
3+
import lombok.extern.slf4j.Slf4j;
4+
import org.aspectj.lang.JoinPoint;
5+
import org.aspectj.lang.annotation.After;
6+
import org.aspectj.lang.annotation.Aspect;
7+
import org.aspectj.lang.annotation.Before;
8+
import org.springframework.core.annotation.Order;
9+
import org.springframework.stereotype.Component;
10+
import top.cadecode.common.datasource.DynamicDataSource.DynamicDataSourceHolder;
11+
12+
/**
13+
* @author Li Jun
14+
* @date 2021/12/3
15+
* @description 动态数据源切换 AOP 类
16+
*/
17+
@Slf4j
18+
@Aspect
19+
@Component
20+
@Order(-1) // 设置 Order 使切面在 @Transactional 之前执行
21+
public class DynamicDataSourceAspect {
22+
23+
/**
24+
* 切换数据源
25+
*/
26+
@Before("@annotation(dataSource)")
27+
public void switchDataSource(JoinPoint point, DataSource dataSource) {
28+
String dataSourceKey = dataSource.value();
29+
if (!DynamicDataSourceHolder.containDataSourceKey(dataSourceKey)) {
30+
log.info("数据源 {} 不存在,将使用默认数据源", dataSource.value());
31+
} else {
32+
// 切换数据源
33+
DynamicDataSourceHolder.setDataSourceKey(dataSource.value());
34+
log.info("切换数据源到 {},在方法 [{}]", dataSourceKey, point.getSignature());
35+
}
36+
}
37+
38+
/**
39+
* 重置数据源
40+
*/
41+
@After("@annotation(dataSource)")
42+
public void resetDataSource(JoinPoint point, DataSource dataSource) {
43+
// 将数据源重置置为默认数据源
44+
DynamicDataSourceHolder.clearDataSourceKey();
45+
log.info("重置默认数据源,在方法 [{}]", point.getSignature());
46+
}
47+
48+
}

0 commit comments

Comments
 (0)