提交 | 用户 | 时间
|
e7c126
|
1 |
package com.iailab.framework.tenant.core.context; |
H |
2 |
|
|
3 |
import cn.hutool.core.util.StrUtil; |
|
4 |
import com.iailab.framework.common.enums.DocumentEnum; |
|
5 |
import com.alibaba.ttl.TransmittableThreadLocal; |
|
6 |
|
|
7 |
/** |
|
8 |
* 多租户上下文 Holder |
|
9 |
* |
|
10 |
* @author iailab |
|
11 |
*/ |
|
12 |
public class TenantContextHolder { |
|
13 |
|
|
14 |
/** |
|
15 |
* 当前租户编号 |
|
16 |
*/ |
|
17 |
private static final ThreadLocal<Long> TENANT_ID = new TransmittableThreadLocal<>(); |
|
18 |
|
|
19 |
/** |
|
20 |
* 是否忽略租户 |
|
21 |
*/ |
|
22 |
private static final ThreadLocal<Boolean> IGNORE = new TransmittableThreadLocal<>(); |
|
23 |
|
|
24 |
/** |
|
25 |
* 获得租户编号 |
|
26 |
* |
|
27 |
* @return 租户编号 |
|
28 |
*/ |
|
29 |
public static Long getTenantId() { |
|
30 |
return TENANT_ID.get(); |
|
31 |
} |
|
32 |
|
|
33 |
/** |
|
34 |
* 获得租户编号。如果不存在,则抛出 NullPointerException 异常 |
|
35 |
* |
|
36 |
* @return 租户编号 |
|
37 |
*/ |
|
38 |
public static Long getRequiredTenantId() { |
|
39 |
Long tenantId = getTenantId(); |
|
40 |
if (tenantId == null) { |
|
41 |
throw new NullPointerException("TenantContextHolder 不存在租户编号!可参考文档:" |
|
42 |
+ DocumentEnum.TENANT.getUrl()); |
|
43 |
} |
|
44 |
return tenantId; |
|
45 |
} |
|
46 |
|
|
47 |
public static void setTenantId(Long tenantId) { |
|
48 |
TENANT_ID.set(tenantId); |
|
49 |
} |
|
50 |
|
|
51 |
public static void setIgnore(Boolean ignore) { |
|
52 |
IGNORE.set(ignore); |
|
53 |
} |
|
54 |
|
|
55 |
/** |
|
56 |
* 当前是否忽略租户 |
|
57 |
* |
|
58 |
* @return 是否忽略 |
|
59 |
*/ |
|
60 |
public static boolean isIgnore() { |
|
61 |
return Boolean.TRUE.equals(IGNORE.get()); |
|
62 |
} |
|
63 |
|
|
64 |
public static void clear() { |
|
65 |
TENANT_ID.remove(); |
|
66 |
IGNORE.remove(); |
|
67 |
} |
|
68 |
|
|
69 |
} |