zhaowenxuan
2025-03-21 02b4c9fd4c5ff7c77553fd4bf0f07d4b21ae8f09
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
package com.ltkj.framework.aspectj;
 
import com.ltkj.db.DataSourceContextHolder;
import com.ltkj.framework.datasource.DynamicDataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
 
/**
 * ClassName: AsynAspect <br/>
 * Description: 在异步方法执行时,获取并传递当前线程的数据源。<br/>
 * date: 2025/2/15 18:07<br/>
 *
 * @author zjh<br />
 */
//@Aspect
//@Component
public class AsynAspect {
 
    private static final Logger logger = LoggerFactory.getLogger(AsynAspect.class);
 
    @Pointcut("@annotation(org.springframework.scheduling.annotation.Async) || @within(org.springframework.scheduling.annotation.Async)")
    public void asyncPointCut() {
        // 异步方法切入点
    }
 
    @Around("asyncPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        // 获取当前线程的 DataSource
        String currentDataSource = DataSourceContextHolder.getDataSourceKey();
 
        logger.info("当前线程数据源: {}", currentDataSource);
 
        // 在异步方法执行前,设置数据源到 DynamicDataSourceContextHolder
        DynamicDataSourceContextHolder.setDataSourceType(currentDataSource);
 
        try {
            // 执行异步方法
            return point.proceed();
        } finally {
            // 执行完毕后清理数据源
            DynamicDataSourceContextHolder.clearDataSourceType();
            logger.info("清理数据源,恢复默认数据源");
        }
    }
}