Home  >  Article  >  Java  >  How to add Guava Cache to SpringBoot to implement local caching

How to add Guava Cache to SpringBoot to implement local caching

王林
王林forward
2023-05-12 22:22:121304browse

Add guava dependency in pom.xml

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

Create a CacheService to facilitate calling

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

Implementation class

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<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);
  }
}

The above is the detailed content of How to add Guava Cache to SpringBoot to implement local caching. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete