GuavaCacheUtil.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package nju.seec.helper.util;
  2. import com.google.common.cache.Cache;
  3. import com.google.common.cache.CacheBuilder;
  4. import com.google.common.collect.ImmutableMap;
  5. import org.springframework.beans.factory.BeanNameAware;
  6. import org.springframework.beans.factory.InitializingBean;
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.stereotype.Component;
  9. import org.springframework.util.StringUtils;
  10. import java.util.Collection;
  11. import java.util.List;
  12. import java.util.Map;
  13. import java.util.concurrent.TimeUnit;
  14. import java.util.stream.Collectors;
  15. @Component
  16. public class GuavaCacheUtil {
  17. private Cache<Object, Object> cache;
  18. @Value("${guavaCache.maximumSize}")
  19. private Long maximumSize=1000L;
  20. @Value("${guavaCache.expireAfterAccessInSeconds}")
  21. private Long expireAfterAccessInSeconds=1800L;
  22. @Value("${guavaCache.expireAfterWriteInSeconds}")
  23. private Long expireAfterWriteInSeconds=3600L;
  24. public GuavaCacheUtil() {
  25. CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
  26. builder.maximumSize(maximumSize);
  27. builder.expireAfterAccess(expireAfterAccessInSeconds, TimeUnit.SECONDS);
  28. builder.expireAfterWrite(expireAfterWriteInSeconds, TimeUnit.SECONDS);
  29. cache = builder.build();
  30. }
  31. public void set(String cacheName, String key, Object value) {
  32. cache.put(combineKey(cacheName,key),value);
  33. }
  34. public void setAll(String cacheName, Map<String,Object> putAll) {
  35. final Map<String, Object> all = putAll.entrySet().stream().collect(Collectors.toMap(entry -> {
  36. return combineKey(cacheName , entry.getKey());
  37. }, Map.Entry::getValue));
  38. cache.putAll(all);
  39. }
  40. public Object get(String cacheName, String key) {
  41. return cache.getIfPresent(combineKey(cacheName,key));
  42. }
  43. public ImmutableMap<Object, Object> multiGet(String cacheName, Collection<String> keys) {
  44. Collection<String> body=keys.stream().map(s->combineKey(cacheName,s)).collect(Collectors.toList());
  45. return cache.getAllPresent(body);
  46. }
  47. public void remove(String cacheName, String key) {
  48. cache.invalidate(combineKey(cacheName,key));
  49. }
  50. private String combineKey(String cacheName, String key){
  51. return cacheName + ":" + key;
  52. }
  53. }