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

How to add Guava Cache to SpringBoot to implement local caching

王林
Release: 2023-05-12 22:22:12
forward
1318 people have browsed it

Add guava dependency in pom.xml

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

Create a CacheService to facilitate calling

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

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);
  }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template