提交 | 用户 | 时间
|
e7c126
|
1 |
package com.iailab.framework.tenant.core.util; |
H |
2 |
|
|
3 |
import com.iailab.framework.tenant.core.context.TenantContextHolder; |
|
4 |
|
|
5 |
import java.util.Map; |
|
6 |
import java.util.concurrent.Callable; |
|
7 |
|
|
8 |
import static com.iailab.framework.web.core.util.WebFrameworkUtils.HEADER_TENANT_ID; |
|
9 |
|
|
10 |
/** |
|
11 |
* 多租户 Util |
|
12 |
* |
|
13 |
* @author iailab |
|
14 |
*/ |
|
15 |
public class TenantUtils { |
|
16 |
|
|
17 |
/** |
|
18 |
* 使用指定租户,执行对应的逻辑 |
|
19 |
* |
|
20 |
* 注意,如果当前是忽略租户的情况下,会被强制设置成不忽略租户 |
|
21 |
* 当然,执行完成后,还是会恢复回去 |
|
22 |
* |
|
23 |
* @param tenantId 租户编号 |
|
24 |
* @param runnable 逻辑 |
|
25 |
*/ |
|
26 |
public static void execute(Long tenantId, Runnable runnable) { |
|
27 |
Long oldTenantId = TenantContextHolder.getTenantId(); |
|
28 |
Boolean oldIgnore = TenantContextHolder.isIgnore(); |
|
29 |
try { |
|
30 |
TenantContextHolder.setTenantId(tenantId); |
|
31 |
TenantContextHolder.setIgnore(false); |
|
32 |
// 执行逻辑 |
|
33 |
runnable.run(); |
|
34 |
} finally { |
|
35 |
TenantContextHolder.setTenantId(oldTenantId); |
|
36 |
TenantContextHolder.setIgnore(oldIgnore); |
|
37 |
} |
|
38 |
} |
|
39 |
|
|
40 |
/** |
|
41 |
* 使用指定租户,执行对应的逻辑 |
|
42 |
* |
|
43 |
* 注意,如果当前是忽略租户的情况下,会被强制设置成不忽略租户 |
|
44 |
* 当然,执行完成后,还是会恢复回去 |
|
45 |
* |
|
46 |
* @param tenantId 租户编号 |
|
47 |
* @param callable 逻辑 |
|
48 |
*/ |
|
49 |
public static <V> V execute(Long tenantId, Callable<V> callable) { |
|
50 |
Long oldTenantId = TenantContextHolder.getTenantId(); |
|
51 |
Boolean oldIgnore = TenantContextHolder.isIgnore(); |
|
52 |
try { |
|
53 |
TenantContextHolder.setTenantId(tenantId); |
|
54 |
TenantContextHolder.setIgnore(false); |
|
55 |
// 执行逻辑 |
|
56 |
return callable.call(); |
|
57 |
} catch (Exception e) { |
|
58 |
throw new RuntimeException(e); |
|
59 |
} finally { |
|
60 |
TenantContextHolder.setTenantId(oldTenantId); |
|
61 |
TenantContextHolder.setIgnore(oldIgnore); |
|
62 |
} |
|
63 |
} |
|
64 |
|
|
65 |
/** |
|
66 |
* 忽略租户,执行对应的逻辑 |
|
67 |
* |
|
68 |
* @param runnable 逻辑 |
|
69 |
*/ |
|
70 |
public static void executeIgnore(Runnable runnable) { |
|
71 |
Boolean oldIgnore = TenantContextHolder.isIgnore(); |
|
72 |
try { |
|
73 |
TenantContextHolder.setIgnore(true); |
|
74 |
// 执行逻辑 |
|
75 |
runnable.run(); |
|
76 |
} finally { |
|
77 |
TenantContextHolder.setIgnore(oldIgnore); |
|
78 |
} |
|
79 |
} |
|
80 |
|
|
81 |
/** |
|
82 |
* 将多租户编号,添加到 header 中 |
|
83 |
* |
|
84 |
* @param headers HTTP 请求 headers |
|
85 |
* @param tenantId 租户编号 |
|
86 |
*/ |
|
87 |
public static void addTenantHeader(Map<String, String> headers, Long tenantId) { |
|
88 |
if (tenantId != null) { |
|
89 |
headers.put(HEADER_TENANT_ID, tenantId.toString()); |
|
90 |
} |
|
91 |
} |
|
92 |
|
|
93 |
} |