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 caches = new ConcurrentHashMap<>(); public T get(Class clazz) { return (T) get(clazz.getName()); } public Object get(String key) { return get(key, true); } public T get(String key, Supplier 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); } }