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
* Description: 在异步方法执行时,获取并传递当前线程的数据源。
* date: 2025/2/15 18:07
*
* @author zjh
*/
//@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("清理数据源,恢复默认数据源");
}
}
}