SpringBoot中怎么利用GuavaCache实现本地缓存

SpringBoot中怎么利用GuavaCache实现本地缓存,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

在pom.xml中加入guava依赖

<dependency>    <groupId>com.google.guava</groupId>    <artifactId>guava</artifactId>    <version>18.0</version>   </dependency>

创建一个CacheService,方便调用

public interface CacheService {  //存  void setCommonCache(String key,Object value);  //取  Object getCommonCache(String key);}

其实现类

import com.google.common.cache.Cache;import com.google.common.cache.CacheBuilder;import com.wu.service.CacheService;import org.springframework.stereotype.Service;import javax.annotation.PostConstruct;import java.util.concurrent.TimeUnit;@Servicepublic class CacheServiceImpl implements CacheService {  private Cache<String,Object> commonCache=null;  @PostConstruct//代理此bean时会首先执行该初始化方法  public void init(){    commonCache= CacheBuilder.newBuilder()        //设置缓存容器的初始化容量为10(可以存10个键值对)        .initialCapacity(10)        //最大缓存容量是100,超过100后会安装LRU策略-最近最少使用,具体百度-移除缓存项        .maximumSize(100)        //设置写入缓存后1分钟后过期        .expireAfterWrite(60, TimeUnit.SECONDS).build();  }  @Override  public void setCommonCache(String key, Object value) {    commonCache.put(key,value);  }  @Override  public Object getCommonCache(String key) {    return commonCache.getIfPresent(key);  }}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对亿速云的支持。