这篇文章主要介绍了SpringBoot加入Guava Cache实现本地缓存代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
在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;
@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);
}
}