dengzedong
2024-10-14 3e18d4bfbf2c657b08b21512c2d884cc9d59df7b
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
package com.iailab.framework.tenant.core.context;
 
import com.alibaba.ttl.TransmittableThreadLocal;
import com.iailab.framework.common.enums.DocumentEnum;
 
/**
 * 数据源上下文 Holder
 *
 * @author iailab
 */
public class DataContextHolder {
 
    /**
     * 数据源id
     */
    private static final ThreadLocal<Long> DATA_SOURCE_ID =  new TransmittableThreadLocal<>();
 
    /**
     * 数据源id
     *
     * @return 租户编号
     */
    public static Long getDataSourceId() {
        return DATA_SOURCE_ID.get();
    }
 
    /**
     * 数据源id。如果不存在,则抛出 NullPointerException 异常
     *
     * @return 租户编号
     */
    public static Long getRequiredDataSourceId() {
        Long dataSourceId = getDataSourceId();
        if (dataSourceId == null) {
            throw new NullPointerException("DataContextHolder 不存在数据源id!可参考文档:"
                + DocumentEnum.TENANT.getUrl());
        }
        return dataSourceId;
    }
 
    public static void setDataSourceId(Long dataSourceId) {
        DATA_SOURCE_ID.set(dataSourceId);
    }
 
}