SpringBoot中的缓存技术来提高系统性能。在使用SpringBoot缓存技术使用比较简单,但也需要注意一些问题。本节先介绍 Spring Boot 自带的in-memory缓存,然后再介绍 EhCahce 和 Redis 缓存。一般in-memory缓存仅单体应用或者是一个小微系统,不适合用在分布式环境下。通常应用为分布式应用时,则需要集成 EhCache、Redis 等分布式缓存管理器。
为什么使用Spring Cache
没有SpringBoot之前,我们集成缓存,一般都是通过根据缓存技术提供的接口来实现缓存,每种缓存都需要单独实现,需要考虑线程安全,缓存过期,缓存高可用等等,不是一件简单的事。而Spring Cache 对 Cahce 进行了抽象,提供了 @Cacheable、@CachePut、@CacheEvict 等注解。Spring Boot 应用基于 Spring Cache,既提供了基于内存实现的缓存管理器,可以用于单体应用系统,也集成了 EhCache、Redis 等缓存服务器,可以用于大型系统或者分布式系统,因此可以根据自己的项目需求选择合理的缓存方案。关键它可以通过注解配置方式低侵入的给原有Spring应用增加缓存功能,提高数据访问性能。在Spring Boot中对于缓存的支持,提供了一系列的自动化配置,使我们可以非常方便的使用缓存。我们也可以轻易的在不同缓存方案中切换,无需修改任何代码。
Spring cache核心组件
Java Caching定义了5个核心接口,分别是CachingProvider, CacheManager, Cache, Entry 和 Expiry。定义摘抄如下,从图上就能很好的理解它们之间的关系。
![8641918b78c80c94b0a713818acde7ce.png](https://img-blog.csdnimg.cn/img_convert/8641918b78c80c94b0a713818acde7ce.png)
CachingProvider: Create, configure, acquire, manage, and control multiple CacheManager
CacheManager: Create, configure, acquire, manage, and control multiple uniquely named Caches that exist within the context of CacheManager.A CacheManager corresponds to only one CachingProvider
Cache:is managed by Cache Manager, which manages the life cycle of Cache. Cache exists in the context of Cache Manager and is a map-like data structure that temporarily stores key-indexed values.A Cache is owned by only one CacheManager
Entry:is a key-value pair stored in a Cache
Expiry: Each entry stored in a Cache has a defined expiration date.Once this time is exceeded, the entries will automatically expire, after which they will not be accessible, updated, and deleted.Cache validity can be set through ExpiryPolicy。
SpringBoot Cache常见注解
@CacheConfig,在类上设置当前缓存的一些公共设置,比如缓存名称;
@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface CacheConfig { String[] cacheNames() default {}; String keyGenerator() default ""