在pom.xml中加入guava依赖

   
    com.google.guava
    guava
    18.0
   

创建一个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;
@Service
public class CacheServiceImpl implements CacheService {
  private Cache 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);
  }
}
本文转载于:https://www.yisu.com/zixun/366819.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。