懒羊羊
2024-01-10 39a1dbf748fda65d211fc1f59f41621fc84351ec
提交 | 用户 | 时间
71e81e 1 package cn.stylefeng.guns.tenant.aop;
2
3 import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
4 import cn.stylefeng.guns.base.consts.ConstantsContext;
5 import cn.stylefeng.guns.base.tenant.context.DataBaseNameHolder;
6 import cn.stylefeng.guns.base.tenant.context.TenantCodeHolder;
7 import cn.stylefeng.roses.core.mutidatasource.DataSourceContextHolder;
8 import cn.stylefeng.roses.core.util.ToolUtil;
9 import org.aspectj.lang.ProceedingJoinPoint;
10 import org.aspectj.lang.annotation.Around;
11 import org.aspectj.lang.annotation.Aspect;
12 import org.aspectj.lang.annotation.Pointcut;
13 import org.slf4j.Logger;
14 import org.slf4j.LoggerFactory;
15 import org.springframework.core.Ordered;
16 import org.springframework.stereotype.Component;
17
18 /**
19  * 租户的多数据源切换的aop
20  *
21  * @author fengshuonan
22  * @date 2017年3月5日 上午10:22:16
23  */
24 @Aspect
25 @Component
26 public class TenantSourceExAop implements Ordered {
27
28     private Logger log = LoggerFactory.getLogger(this.getClass());
29
30     /**
31      * 拦截控制器层
32      */
33     @Pointcut("execution(* *..controller.*.*(..))")
34     public void cutService() {
35     }
36
37     @Around("cutService()")
38     public Object around(ProceedingJoinPoint point) throws Throwable {
39         try {
40             //根据系统总开关来进行aop,获取当前用户登录的租户标识
41             if (ConstantsContext.getTenantOpen()) {
42                 if (LoginContextHolder.getContext().hasLogin()) {
43                     String dataSourceName = LoginContextHolder.getContext().getUser().getTenantDataSourceName();
44                     if (ToolUtil.isNotEmpty(dataSourceName)) {
45                         DataSourceContextHolder.setDataSourceType(dataSourceName);
46                         log.debug("多租户AOP--TenantSourceExAop--设置数据源为:" + dataSourceName);
47                     }
48                 }
49             }
50             return point.proceed();
51         } finally {
52             log.debug("多租户AOP--TenantSourceExAop--清空数据源信息!");
53             DataSourceContextHolder.clearDataSourceType();
54             TenantCodeHolder.remove();
55             DataBaseNameHolder.remove();
56         }
57     }
58
59     /**
60      * aop的顺序要早于多数据源切换的
61      */
62     @Override
63     public int getOrder() {
64         return -100;
65     }
66
67 }