package com.dy.common.multiDataSource;
|
|
import com.dy.common.contant.Constant;
|
import com.mysql.jdbc.StringUtils;
|
import lombok.extern.slf4j.Slf4j;
|
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.aspectj.lang.reflect.MethodSignature;
|
import org.springframework.core.annotation.Order;
|
import org.springframework.stereotype.Component;
|
|
import java.lang.reflect.Method;
|
import java.util.Objects;
|
|
@Slf4j
|
@Aspect
|
@Order(Constant.AspectOrderDataSource)
|
@Component
|
public class DataSourceAspect {
|
|
@Pointcut("@annotation(com.dy.common.multiDataSource.DataSource)")
|
public void dataSourcePointCut() {
|
}
|
|
@Around("dataSourcePointCut()")
|
public Object around(ProceedingJoinPoint point) throws Throwable {
|
MethodSignature signature = (MethodSignature) point.getSignature();
|
Method method = signature.getMethod();
|
DataSource dataSource = method.getAnnotation(DataSource.class);
|
|
if (Objects.nonNull(dataSource) && !StringUtils.isNullOrEmpty(dataSource.value())) {
|
log.info("切换数据源为" + dataSource.value());
|
//强制转成方法上配置的数据源,替换掉DataSourceContext中保存的数据源
|
DataSourceContext.set(dataSource.value());
|
}else{
|
String dataSourceName = DataSourceContext.get() ;
|
if(!StringUtils.isNullOrEmpty(dataSourceName)){
|
log.info("当前数据源为" + dataSourceName);
|
}
|
}
|
|
try {
|
log.info("数据库操作开始" + dataSource.value());
|
return point.proceed();
|
} finally {
|
// 销毁数据源 在执行方法之后
|
log.info("数据源操作完毕" + dataSource.value());
|
DataSourceContext.remove();
|
}
|
}
|
|
}
|