package nju.seec.helper.util.cache; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.ImmutableMap; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.Collection; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * @author xst *

* updated by cst */ @Component public class GuavaCacheUtils { private Cache cache; public GuavaCacheUtils(@Value("${guavaCache.maximumSize}") Long maximumSize, @Value("${guavaCache.expireAfterAccessInSeconds}") Long expireAfterAccessInSeconds, @Value("${guavaCache.expireAfterWriteInSeconds}") Long expireAfterWriteInSeconds) { cache = CacheBuilder .newBuilder() .maximumSize(maximumSize) .expireAfterAccess(expireAfterAccessInSeconds, TimeUnit.SECONDS) .expireAfterWrite(expireAfterWriteInSeconds, TimeUnit.SECONDS) .build(); } public void set(String cacheName, String key, Object value) { cache.put(combineKey(cacheName, key), value); } public void setAll(String cacheName, Map putAll) { final Map all = putAll.entrySet().stream().collect(Collectors.toMap(entry -> combineKey(cacheName, entry.getKey()), Map.Entry::getValue)); cache.putAll(all); } public Object get(String cacheName, String key) { return cache.getIfPresent(combineKey(cacheName, key)); } public ImmutableMap multiGet(String cacheName, Collection keys) { Collection body = keys.stream().map(s -> combineKey(cacheName, s)).collect(Collectors.toList()); return cache.getAllPresent(body); } public void remove(String cacheName, String key) { cache.invalidate(combineKey(cacheName, key)); } private String combineKey(String cacheName, String key) { return cacheName + ":" + key; } }