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);
|
}
|
}
|