SpringBoot加入Guava Cache实现本地缓存

也可以参考  这里

在pom.xml中加入guava依赖

1     <dependency>
2       <groupId>com.google.guava</groupId>
3       <artifactId>guava</artifactId>
4       <version>18.0</version>
5     </dependency>

创建一个CacheService,方便调用

1 public interface CacheService {
2     //
3     void setCommonCache(String key,Object value);
4     //
5     Object getCommonCache(String key);
6 }

其实现类

 1 import com.google.common.cache.Cache;
 2 import com.google.common.cache.CacheBuilder;
 3 import com.wu.service.CacheService;
 4 import org.springframework.stereotype.Service;
 5 import javax.annotation.PostConstruct;
 6 import java.util.concurrent.TimeUnit;
 7 @Service
 8 public class CacheServiceImpl implements CacheService {
 9 
10     private Cache<String,Object> commonCache=null;
11 
12     @PostConstruct//代理此bean时会首先执行该初始化方法
13     public void init(){
14         commonCache= CacheBuilder.newBuilder()
15                 //设置缓存容器的初始化容量为10(可以存10个键值对)
16                 .initialCapacity(10)
17                 //最大缓存容量是100,超过100后会安装LRU策略-最近最少使用,具体百度-移除缓存项
18                 .maximumSize(100)
19                 //设置写入缓存后1分钟后过期
20                 .expireAfterWrite(60, TimeUnit.SECONDS).build();
21     }
22 
23     @Override
24     public void setCommonCache(String key, Object value) {
25         commonCache.put(key,value);
26     }
27 
28     @Override
29     public Object getCommonCache(String key) {
30         return commonCache.getIfPresent(key);
31     }
32 }

猜你喜欢

转载自www.cnblogs.com/wuba/p/11458276.html
今日推荐