luxiaotao1123
2024-06-21 569d2b6bc754b037ade5b4205a4d1cdb8339b26b
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
69
70
71
72
package com.zy.asrs.framework.common;
 
import com.zy.asrs.framework.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<>();
    
    @SuppressWarnings("unchecked")
    public <T>T get(Class<T> prototype) {
        return (T) get(prototype.getName());
    }
    
    public Object get(String key) {
        return get(key,true);
    }
    
    @SuppressWarnings("unchecked")
    public <T>T get(String key,Supplier<T> func){
        if(!hasKey(key)) {
            put(key,func.get());
        }
        return (T)get(key);
    }
    
    public Object get(String key,boolean exist) {
        if(exist) {
            if(!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 exist) {
        if(exist) {
            if(hasKey(key)) {
                throw new ApplicationException(this+"-缓存"+key+"已存在");
            }
        }
        caches.put(key, value);
        return this;
    }
    
    public boolean hasKey(Class<?> prototype) {
        return hasKey(prototype.getName());
    }
    
    public boolean hasKey(String key) {
        return caches.containsKey(key);
    }
    
}