liurunyu
2023-11-04 df37487916ebc1ff8d8e0f8b088c5b6af1e582ff
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
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();
        }
    }
 
}