危化品全生命周期管理后端
kongzy
2024-08-22 0c73654f55844e34772732914af8cc1e247aab63
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
55
56
57
58
59
package com.gkhy.hazmat.common.config;
 
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import com.gkhy.hazmat.common.utils.StringUtils;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 * 自定义动态表名处理器,基于id的方式进行分表
 */
public class IdTableNameHandler implements TableNameHandler {
    private static final Map<String,Integer> CONFIG_TABLE_INFO_MAP=new HashMap<>();
 
    static {
        CONFIG_TABLE_INFO_MAP.put("hz_hazmat",20);
        CONFIG_TABLE_INFO_MAP.put("hz_hazmat_flow",20);
        CONFIG_TABLE_INFO_MAP.put("hz_product",20);
        CONFIG_TABLE_INFO_MAP.put("hz_product_flow",20);
    }
 
    private static final ThreadLocal<Long> ID_DATA=new ThreadLocal<>();
    @Override
    public String dynamicTableName(String sql, String tableName) {
        if(StringUtils.isBlank(tableName)||!CONFIG_TABLE_INFO_MAP.containsKey(tableName)){
            return tableName;
        }
        //分表个数
        int tableSize=CONFIG_TABLE_INFO_MAP.get(tableName);
        //当前分表的id
        Long currentId=getCurrentId();
        if(currentId==null){
            throw new RuntimeException("请设置分表id值");
        }
        int tableIndex= (int) (currentId%tableSize);
 
        //清理当前id
  //      removeCurrentId();
 
        return tableName+"_"+tableIndex;
    }
 
    /**
     * 获取当前分表id
     * @param id
     */
    public static void setCurrentId(Long id){
        ID_DATA.set(id);
    }
 
    public static Long getCurrentId(){
        return ID_DATA.get();
    }
 
    public static void removeCurrentId(){
        ID_DATA.remove();
    }
 
}