参考资料
Spring Boot缓存注解@Cacheable、@CacheEvict、@CachePut使用:https://blog.csdn.net/dreamhai/article/details/80642010
官方文档:https://docs.spring.io/spring-boot/docs/2.1.7.RELEASE/reference/htmlsingle/#boot-features-caching
Spring使用Cache:https://www.iteye.com/blog/elim-2123030
配置方式
加载maven
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
直接在启动类上添加@EnableCaching注解即可使用
@SpringBootApplication @EnableCaching public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
如果未配置缓存方式,Spring Boot会自动配置一个在内存中使用可以在并发环境中使用的的缓存。
可配置属性
spring.cache.cache-names= # 如果底层缓存管理器支持,则创建的以逗号分隔的缓存名称列表。 spring.cache.caffeine.spec= # 用于创建缓存的规范。 有关规格格式的更多详细信息,请参阅CaffeineSpec. spring.cache.couchbase.expiration= # 生效到期。 默认情况下,缓存永不过期。 请注意,此值最终会转换为秒。 spring.cache.ehcache.config= # 用于初始化EhCache的配置文件的位置。 spring.cache.infinispan.config= # 用于初始化Infinispan的配置文件的位置。 spring.cache.jcache.config= # 用于初始化缓存管理器的配置文件的位置。 spring.cache.jcache.provider= # 用于检索符合JSR-107的缓存管理器的CachingProvider实现的完全限定名称。 仅当类路径上有多个JSR-107实现时才需要。 spring.cache.redis.cache-null-values=true # 允许缓存空值。 spring.cache.redis.key-prefix= # 缓存键值对前缀 spring.cache.redis.time-to-live= # 缓存时间。 默认情况下,条目永不过期。 spring.cache.redis.use-key-prefix=true # 写入Redis时是否使用密钥前缀。 spring.cache.type=no # 不使用缓存,缓存类型。 默认情况下,根据环境自动检测。
可配置缓存形式
缓存抽象不提供实际存储,而是依赖于org.springframework.cache.Cache和org.springframework.cache.CacheManager接口实现的抽象。
如果未配置,Spring Boot则会按照下列方式:
- Generic
- JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, and others)
- EhCache 2.x
- Hazelcast
- Infinispan
- Couchbase
- Redis
- Caffeine
- Simple
也可以通过设置spring.cache.type属性来强制指定缓存的方式。
本文章主要关注EhCache 2.x、Redis、Simple(默认)三种缓存形式。