package nju.seec.helper.util; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.ImmutableMap; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @Component public class GuavaCacheUtil { private Cache cache; @Value("${guavaCache.maximumSize}") private Long maximumSize=1000L; @Value("${guavaCache.expireAfterAccessInSeconds}") private Long expireAfterAccessInSeconds=1800L; @Value("${guavaCache.expireAfterWriteInSeconds}") private Long expireAfterWriteInSeconds=3600L; public GuavaCacheUtil() { CacheBuilder builder = CacheBuilder.newBuilder(); builder.maximumSize(maximumSize); builder.expireAfterAccess(expireAfterAccessInSeconds, TimeUnit.SECONDS); builder.expireAfterWrite(expireAfterWriteInSeconds, TimeUnit.SECONDS); cache = builder.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 -> { return 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; } }