1. 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2. 配置类
package com.llscz.datejiang.config;
import org.springframework.cache.CacheManager;
import org.springframework.cache.guava.GuavaCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author sukaiyi
*/
@Configuration
public class CacheConfig {
@Bean
public CacheManager getCacheManager() {
GuavaCacheManager cacheManager = new GuavaCacheManager();
//最多缓存500 条,失效时间120分钟
cacheManager.setCacheSpecification("maximumSize=500,expireAfterWrite=120m");
//GuavaCacheManager 的数据结构类似 Map<String,Map<Object,Object>> map =new HashMap<>();
return cacheManager;
}
}
3. 使用
@Autowired
CacheManager cacheManager;
//存
cacheManager.getCache("wx.app").put("access_token", accessToken);
//取
Cache.ValueWrapper wrapper = cacheManager.getCache("wx.app").get("access_token");
if (wrapper == null) {
// 没有缓存
} else {
String value = wrapper.get().toString();
}
网友评论