| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- 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
- * <p>
- * updated by cst
- */
- @Component
- public class GuavaCacheUtils {
- private Cache<Object, Object> 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<String, Object> putAll) {
- final Map<String, Object> 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<Object, Object> multiGet(String cacheName, Collection<String> keys) {
- Collection<String> 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;
- }
- }
|