Spring Boot提供了spring-boot-starter-cache,支持多个缓存实现,如EHCache,Redis,GUAVA etc...,此处以轻量GUAVA为例:
一. 基本使用
0. 首先需要加入依赖,版本根据自己需求指定
org.springframework.boot spring-boot-starter-cache ${v} com.google.guava guava ${v}
1. 开启缓存,在Application类加入@EnableCaching
2. 通过@Cacheable使用缓存
@Cacheable("{cacheNames}")public Object needCache() { return ...;}
二. 指定缓存参数[以过期时间为例,不同的数据类型要求的缓存时间不同]
Spring boot提供基于application.xx的配置
spring.cache.type=GUAVAspring.cache.cache-names=cacheName# 参数参考com.google.common.cache.CacheBuilderSpecspring.cache.guava.spec=expireAfterWrite=7m
这种配置方式,只能提供一种策略的缓存(如果有直接基于配置配置文件的多种策略配置,请留言),如果不同缓存策略需要通过自定义配置:
@Configurationpublic class CacheConfig { /** * Define cache strategy * * @return CacheManager */ @Bean public CacheManager cacheManager() { SimpleCacheManager simpleCacheManager = new SimpleCacheManager(); Listcaches = new ArrayList<>(); # 缓存5min后失效 caches.add(new GuavaCache("{cacheName}", CacheBuilder.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES).build())); simpleCacheManager.setCaches(caches); return simpleCacheManager; }}
配置完成发现spring推荐使用caffeine取代guava,所以改为使用caffeine作为实现。
PS: ,,