#
Junjie
1 天以前 536e17a446c170a8b214aaf188b98817ee6258c1
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
package com.core.common;
 
import com.core.exception.ApplicationException;
 
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
 
public class Cache {
 
    private Map<String, Object> caches = new ConcurrentHashMap<>();
 
    public <T> T get(Class<T> clazz) {
        return (T) get(clazz.getName());
    }
 
    public Object get(String key) {
        return get(key, true);
    }
 
    public <T> T get(String key, Supplier<T> supplier) {
        if (!hasKey(key)) {
            put(key, supplier.get());
        }
        return (T) get(key);
    }
 
    public Object get(String key, boolean require) {
        if (require && !hasKey(key)) {
            throw new ApplicationException(this + "-找不到缓存对象:" + key);
        }
        return caches.get(key);
    }
 
    public Cache put(Object value) {
        String key = value.getClass().getName();
        put(key, value);
        return this;
    }
 
    public Cache put(String key, Object value) {
        put(key, value, true);
        return this;
    }
 
    public Cache put(String key, Object value, boolean requireNotExists) {
        if (requireNotExists && hasKey(key)) {
            throw new ApplicationException(this + "-缓存" + key + "已存在");
        }
        caches.put(key, value);
        return this;
    }
 
    public boolean hasKey(Class<?> clazz) {
        return hasKey(clazz.getName());
    }
 
    public boolean hasKey(String key) {
        return caches.containsKey(key);
    }
}