fuliqi
2024-07-10 254c2a69441dbd9ee9bcb1d134a05eb9da407d17
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
60
61
62
63
64
65
66
67
68
package com.ycl.jxkg.utils;
 
import com.github.benmanes.caffeine.cache.Cache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
 
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
 
/**
 * caffeine 保存、获取工具
 *
 * @author:xp
 * @date:2024/7/10 11:50
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CaffeineUtil {
 
    private final Cache<String, Object> caffeineCache;
 
    /**
     * 保存
     *
     * @param database 数据库/ caffeine map的key
     * @param key map的key
     * @param value map的value
     */
    public void put(String database, String key, Object value) {
        Map<String, Object> map = (Map<String, Object>) caffeineCache.getIfPresent(database);
        if (Objects.isNull(map)) {
            log.error("缓存异常");
            map = new HashMap<>(128);
            this.createDatabase(database, map);
            return;
        }
        map.put(key, value);
    }
 
    /**
     * 获取
     *
     * @param database 数据库/ caffeine map的key
     * @param key map的key
     */
    public Object get(String database, String key) {
        Map<String, Object> map = (Map<String, Object>) caffeineCache.getIfPresent(database);
        if (Objects.isNull(map)) {
            log.error("缓存异常");
            return null;
        }
        return map.get(key);
    }
 
    /**
     * 创建key
     *
     * @param database
     * @param map
     */
    private void createDatabase(String database, Map<String, Object> map) {
        caffeineCache.put(database, map);
    }
 
}