| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- 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<Object, Object> 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<Object, Object> 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<String,Object> putAll) {
- final Map<String, Object> 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<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;
- }
- }
|