zhizhijie
2026-09-14 d1cfd849c6a61800dcd86ffb45f80882ae20b2e7
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
package com.trafficaudit.llmintegration.service;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
 
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
 
/**
 * 企业名称脱敏:把企业名称替换为 Company1、Company2… 后发给大模型,回答返回前再还原。
 * 仅保存在内存中,不落库。
 */
@Slf4j
@Service
public class DesensitizeService {
 
    private final Map<String, String> enterpriseMap = new ConcurrentHashMap<>();
    private final Map<String, String> reverseMap = new ConcurrentHashMap<>();
    private final AtomicInteger counter = new AtomicInteger(1);
 
    public String maskEnterprise(String name) {
        if (name == null) {
            return null;
        }
        return enterpriseMap.computeIfAbsent(name, k -> {
            String alias = "Company" + counter.getAndIncrement();
            reverseMap.put(alias, name);
            return alias;
        });
    }
 
    public String unmaskEnterprise(String alias) {
        return reverseMap.getOrDefault(alias, alias);
    }
 
    /** 把整段文本里出现过的脱敏别名还原为真实企业名称(回答返回给前端前调用) */
    public String unmaskAll(String text) {
        if (text == null || text.isEmpty() || reverseMap.isEmpty()) {
            return text;
        }
        String out = text;
        for (Map.Entry<String, String> e : reverseMap.entrySet()) {
            if (out.contains(e.getKey())) {
                out = out.replace(e.getKey(), e.getValue());
            }
        }
        return out;
    }
 
    public void clear() {
        enterpriseMap.clear();
        reverseMap.clear();
        counter.set(1);
    }
}