这节我们主要从应用的角度上,讲解下spring Cache在项目的应用。
1、首先引入spring cache的jar包,最好引入下第三方的缓存jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.0-jre</version>
</dependency>
2、开启缓存注解--EnableCaching
@EnableCaching
public class Application {
public static void main(String[] args) {
// aes();
// testJson();
SpringApplication.run(Application.class, args);
}
}
3、自定义CacheManager
@Configuration public class CacheConfig { @Bean @Primary public GuavaCacheManager guavaCacheManager() { GuavaCacheManager guavaCacheManager = new GuavaCacheManager() { /** * 设置数量限制、超时时间 * @param name * @return */ @Override protected com.google.common.cache.Cache<Object, Object> createNativeGuavaCache(String name) { return CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterWrite(24, TimeUnit.HOURS) .build(); } }; guavaCacheManager.setAllowNullValues(false); return guavaCacheManager; } }
4、缓存使用
@GetMapping @ApiOperation("") @Cacheable(key = "'templates'", cacheNames = "templates") public List<Template> obtain() throws Exception { String result = restService.getInfo(tUrl, HttpMethod.GET, headService.headers(null), false, false); JsonNode root = mapper.readTree(result); JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, Template.class); List<Template> list = (List<Template>) mapper.readValue(root.get("root").get("template").toString(), javaType); return list; }
上述代码在第一次的时候,会执行方法中的逻辑,当第二次的时候,变回通过缓存进行获取。