GuavaCacheUtils.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package nju.seec.helper.util.cache;
  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.annotation.Value;
  6. import org.springframework.stereotype.Component;
  7. import java.util.Collection;
  8. import java.util.Map;
  9. import java.util.concurrent.TimeUnit;
  10. import java.util.stream.Collectors;
  11. /**
  12. * @author xst
  13. * <p>
  14. * updated by cst
  15. */
  16. @Component
  17. public class GuavaCacheUtils {
  18. private Cache<Object, Object> cache;
  19. public GuavaCacheUtils(@Value("${guavaCache.maximumSize}") Long maximumSize,
  20. @Value("${guavaCache.expireAfterAccessInSeconds}") Long expireAfterAccessInSeconds,
  21. @Value("${guavaCache.expireAfterWriteInSeconds}") Long expireAfterWriteInSeconds) {
  22. cache = CacheBuilder
  23. .newBuilder()
  24. .maximumSize(maximumSize)
  25. .expireAfterAccess(expireAfterAccessInSeconds, TimeUnit.SECONDS)
  26. .expireAfterWrite(expireAfterWriteInSeconds, TimeUnit.SECONDS)
  27. .build();
  28. }
  29. public void set(String cacheName, String key, Object value) {
  30. cache.put(combineKey(cacheName, key), value);
  31. }
  32. public void setAll(String cacheName, Map<String, Object> putAll) {
  33. final Map<String, Object> all = putAll.entrySet().stream().collect(Collectors.toMap(entry -> combineKey(cacheName, entry.getKey()), Map.Entry::getValue));
  34. cache.putAll(all);
  35. }
  36. public Object get(String cacheName, String key) {
  37. return cache.getIfPresent(combineKey(cacheName, key));
  38. }
  39. public ImmutableMap<Object, Object> multiGet(String cacheName, Collection<String> keys) {
  40. Collection<String> body = keys.stream().map(s -> combineKey(cacheName, s)).collect(Collectors.toList());
  41. return cache.getAllPresent(body);
  42. }
  43. public void remove(String cacheName, String key) {
  44. cache.invalidate(combineKey(cacheName, key));
  45. }
  46. private String combineKey(String cacheName, String key) {
  47. return cacheName + ":" + key;
  48. }
  49. }