import com.google.common.cache.Cache;import com.google.common.cache.CacheBuilder;import com.google.common.cache.RemovalListener;import com.google.common.cache.RemovalNotification;import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.util.List;import java.util.Objects;import java.util.concurrent.TimeUnit;/** * guava cache * */public class LocalCacheUtils { private static final Logger log = LoggerFactory.getLogger(LocalCacheUtils.class); /** * 使用google guava缓存处理 */ private static Cache cache; static { cache = CacheBuilder.newBuilder().maximumSize(10000).expireAfterWrite(24, TimeUnit.HOURS).initialCapacity(10) .removalListener(new RemovalListener () { @Override public void onRemoval(RemovalNotification rn) { if (log.isInfoEnabled()) { log.info("被移除缓存{}:{}", rn.getKey(), rn.getValue()); } } }).build(); } /** * 是否存在 * * @param key * @return */ public static boolean isExist(String key) { if (StringUtils.isBlank(key)) { return false; } return Objects.isNull(cache.getIfPresent(key)) ? false : true; } /** * 获取缓存 * * @param key * @return */ public static String get(String key) { return StringUtils.isNotEmpty(key) ? String.valueOf(cache.getIfPresent(key)) : null; } /** * 放入缓存 * * @param key * @param value */ public static void put(String key, String value) { if (StringUtils.isNotEmpty(key) && value != null) { cache.put(key, value); } } /** * 移除缓存 * * @param key */ public static void remove(String key) { if (StringUtils.isNotEmpty(key)) { cache.invalidate(key); } } /** * 批量删除缓存 * * @param keys */ public static void removeBatch(List keys) { if (keys != null && keys.size() > 0) { cache.invalidateAll(keys); } }}复制代码