缓存
Spring Framework 支持透明地向应用程序添加缓存。其核心是,该抽象将缓存应用于方法,从而根据缓存中可用的信息减少执行次数。缓存逻辑是透明应用的,不会对调用者造成任何干扰。只要通过使用 @EnableCaching 注解启用缓存支持,Spring Boot 就会自动配置缓存基础设施。
| 有关更多详细信息,请查阅 Spring Framework 参考的 相关部分。 |
简而言之,要向服务的操作添加缓存,请在其方法上添加相关注解,如以下示例所示
-
Java
-
Kotlin
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
@Component
public class MyMathService {
@Cacheable("piDecimals")
public int computePiDecimal(int precision) {
...
}
}
import org.springframework.cache.annotation.Cacheable
import org.springframework.stereotype.Component
@Component
class MyMathService {
@Cacheable("piDecimals")
fun computePiDecimal(precision: Int): Int {
...
}
}
此示例演示了在可能开销很大的操作上使用缓存。在调用 computePiDecimal 之前,抽象会在 piDecimals 缓存中查找与 precision 参数匹配的条目。如果找到条目,缓存中的内容会立即返回给调用者,并且不会调用该方法。否则,将调用该方法,并在返回该值之前更新缓存。
您还可以透明地使用标准 JSR-107 (JCache) 注解(例如 @CacheResult)。但是,我们强烈建议您不要混用 Spring Cache 和 JCache 注解。 |
如果您不添加任何特定的缓存库,Spring Boot 会自动配置一个使用内存中并发映射的简单提供程序。当需要缓存(例如前面示例中的 piDecimals)时,此提供程序会为您创建它。简单提供程序不真正推荐用于生产用途,但它非常适合入门并确保您理解这些功能。当您决定要使用的缓存提供程序时,请务必阅读其文档以了解如何配置应用程序使用的缓存。几乎所有提供程序都要求您明确配置应用程序中使用的每个缓存。有些提供了一种通过 spring.cache.cache-names 属性自定义默认缓存的方法。
支持的缓存提供程序
缓存抽象不提供实际存储,而是依赖于由 Cache 和 CacheManager 接口实现的抽象。
如果您尚未定义类型为 CacheManager 的 bean 或名为 cacheResolver 的 CacheResolver(请参阅 CachingConfigurer),Spring Boot 会尝试检测以下提供程序(按所示顺序)
-
JCache (JSR-107)(EhCache 3、Hazelcast、Infinispan 及其他)
如果 CacheManager 由 Spring Boot 自动配置,则可以通过设置 spring.cache.type 属性来 强制 指定特定的缓存提供程序。如果您需要在某些环境(例如测试)中使用无操作缓存,请使用此属性。 |
使用 spring-boot-starter-cache 启动器可以快速添加基本的缓存依赖项。该启动器引入了 spring-context-support。如果您手动添加依赖项,则必须包含 spring-context-support 才能使用 JCache 或 Caffeine 支持。 |
如果 CacheManager 由 Spring Boot 自动配置,您可以在其完全初始化之前通过公开实现 CacheManagerCustomizer 接口的 bean 来进一步调整其配置。以下示例设置了一个标志,表示 null 值不应传递到底层映射
-
Java
-
Kotlin
import org.springframework.boot.cache.autoconfigure.CacheManagerCustomizer;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class MyCacheManagerConfiguration {
@Bean
public CacheManagerCustomizer<ConcurrentMapCacheManager> cacheManagerCustomizer() {
return (cacheManager) -> cacheManager.setAllowNullValues(false);
}
}
import org.springframework.boot.cache.autoconfigure.CacheManagerCustomizer
import org.springframework.cache.concurrent.ConcurrentMapCacheManager
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration(proxyBeanMethods = false)
class MyCacheManagerConfiguration {
@Bean
fun cacheManagerCustomizer(): CacheManagerCustomizer<ConcurrentMapCacheManager> {
return CacheManagerCustomizer { cacheManager ->
cacheManager.isAllowNullValues = false
}
}
}
在前面的示例中,预期是自动配置的 ConcurrentMapCacheManager。如果不是这种情况(您提供了自己的配置或自动配置了不同的缓存提供程序),则不会调用定制器。您可以拥有任意数量的定制器,并且还可以通过使用 @Order 或 Ordered 对它们进行排序。 |
通用
如果上下文定义了 至少 一个 Cache bean,则使用通用缓存。将创建一个包装所有该类型 bean 的 CacheManager。
JCache (JSR-107)
通过类路径上存在 CachingProvider(即,类路径上存在符合 JSR-107 的缓存库)来启动 JCache,并且 spring-boot-starter-cache 启动器提供了 JCacheCacheManager。提供了各种兼容库,Spring Boot 为 Ehcache 3、Hazelcast 和 Infinispan 提供依赖管理。也可以添加任何其他兼容库。
可能会出现多个提供程序的情况,在这种情况下,必须明确指定提供程序。即使 JSR-107 标准不强制规定配置文件的标准化位置,Spring Boot 也会尽力适应使用实现细节设置缓存,如以下示例所示
-
属性
-
YAML
spring.cache.jcache.provider=com.example.MyCachingProvider
spring.cache.jcache.config=classpath:example.xml
# Only necessary if more than one provider is present
spring:
cache:
jcache:
provider: "com.example.MyCachingProvider"
config: "classpath:example.xml"
| 当缓存库同时提供原生实现和 JSR-107 支持时,Spring Boot 优先选择 JSR-107 支持,这样如果切换到不同的 JSR-107 实现,也可以使用相同的功能。 |
Spring Boot 全面支持 Hazelcast。如果存在单个 HazelcastInstance,除非指定了 spring.cache.jcache.config 属性,否则它也会自动重用于 CacheManager。 |
有两种方法可以自定义底层 CacheManager
-
可以通过设置
spring.cache.cache-names属性在启动时创建缓存。如果定义了自定义的Configurationbean,则会使用它来自定义它们。 -
使用
CacheManager的引用调用CacheManagerCustomizerbean 进行完全自定义。
如果定义了标准的 CacheManager bean,它会自动包装在抽象所期望的 CacheManager 实现中。不会对其进行进一步的自定义。 |
Hazelcast
Spring Boot 全面支持 Hazelcast。如果 HazelcastInstance 已自动配置且类路径中存在 com.hazelcast:hazelcast-spring,则它会自动包装在 CacheManager 中。
Hazelcast 可以用作 JCache 兼容缓存或 Spring CacheManager 兼容缓存。当将 spring.cache.type 设置为 hazelcast 时,Spring Boot 将使用基于 CacheManager 的实现。如果您想将 Hazelcast 用作 JCache 兼容缓存,请将 spring.cache.type 设置为 jcache。如果您有多个 JCache 兼容缓存提供程序并想强制使用 Hazelcast,则必须明确设置 JCache 提供程序。 |
Infinispan
Infinispan 没有默认配置文件位置,因此必须明确指定。否则,将使用默认的引导程序。
-
属性
-
YAML
spring.cache.infinispan.config=infinispan.xml
spring:
cache:
infinispan:
config: "infinispan.xml"
可以通过设置 spring.cache.cache-names 属性在启动时创建缓存。如果定义了自定义的 ConfigurationBuilder bean,则会使用它来自定义缓存。
为了与 Spring Boot 的 Jakarta EE 9 基线兼容,必须使用 Infinispan 的 -jakarta 模块。对于每个具有 -jakarta 变体的模块,必须使用该变体代替标准模块。例如,必须使用 infinispan-core-jakarta 和 infinispan-commons-jakarta 代替 infinispan-core 和 infinispan-commons。
Couchbase
如果 Spring Data Couchbase 可用且 Couchbase 已配置,则会自动配置 CouchbaseCacheManager。可以通过设置 spring.cache.cache-names 属性在启动时创建额外的缓存,并且可以使用 spring.cache.couchbase.* 属性配置缓存默认值。例如,以下配置创建了 cache1 和 cache2 缓存,其条目 过期时间 为 10 分钟
-
属性
-
YAML
spring.cache.cache-names=cache1,cache2
spring.cache.couchbase.expiration=10m
spring:
cache:
cache-names: "cache1,cache2"
couchbase:
expiration: "10m"
如果您需要对配置进行更多控制,请考虑注册一个 CouchbaseCacheManagerBuilderCustomizer bean。以下示例显示了一个定制器,它为 cache1 和 cache2 配置了特定的条目过期时间
-
Java
-
Kotlin
import java.time.Duration;
import org.springframework.boot.cache.autoconfigure.CouchbaseCacheManagerBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.couchbase.cache.CouchbaseCacheConfiguration;
@Configuration(proxyBeanMethods = false)
public class MyCouchbaseCacheManagerConfiguration {
@Bean
public CouchbaseCacheManagerBuilderCustomizer myCouchbaseCacheManagerBuilderCustomizer() {
return (builder) -> builder
.withCacheConfiguration("cache1", CouchbaseCacheConfiguration
.defaultCacheConfig().entryExpiry(Duration.ofSeconds(10)))
.withCacheConfiguration("cache2", CouchbaseCacheConfiguration
.defaultCacheConfig().entryExpiry(Duration.ofMinutes(1)));
}
}
import org.springframework.boot.cache.autoconfigure.CouchbaseCacheManagerBuilderCustomizer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.couchbase.cache.CouchbaseCacheConfiguration
import java.time.Duration
@Configuration(proxyBeanMethods = false)
class MyCouchbaseCacheManagerConfiguration {
@Bean
fun myCouchbaseCacheManagerBuilderCustomizer(): CouchbaseCacheManagerBuilderCustomizer {
return CouchbaseCacheManagerBuilderCustomizer { builder ->
builder
.withCacheConfiguration(
"cache1", CouchbaseCacheConfiguration
.defaultCacheConfig().entryExpiry(Duration.ofSeconds(10))
)
.withCacheConfiguration(
"cache2", CouchbaseCacheConfiguration
.defaultCacheConfig().entryExpiry(Duration.ofMinutes(1))
)
}
}
}
Redis
如果 Redis 可用且已配置,则会自动配置 RedisCacheManager。可以通过设置 spring.cache.cache-names 属性在启动时创建额外的缓存,并且可以使用 spring.cache.redis.* 属性配置缓存默认值。例如,以下配置创建了 cache1 和 cache2 缓存,其 存活时间 为 10 分钟
-
属性
-
YAML
spring.cache.cache-names=cache1,cache2
spring.cache.redis.time-to-live=10m
spring:
cache:
cache-names: "cache1,cache2"
redis:
time-to-live: "10m"
默认情况下,会添加一个键前缀,这样,如果两个独立的缓存使用相同的键,Redis 就不会有重叠的键,并且不会返回无效值。如果您创建自己的 RedisCacheManager,我们强烈建议保持此设置启用。 |
您可以通过添加自己的 RedisCacheConfiguration @Bean 来完全控制默认配置。如果您需要自定义默认的序列化策略,这会很有用。 |
如果您需要对配置进行更多控制,请考虑注册一个 RedisCacheManagerBuilderCustomizer bean。以下示例显示了一个定制器,它为 cache1 和 cache2 配置了特定的存活时间
-
Java
-
Kotlin
import java.time.Duration;
import org.springframework.boot.cache.autoconfigure.RedisCacheManagerBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
@Configuration(proxyBeanMethods = false)
public class MyRedisCacheManagerConfiguration {
@Bean
public RedisCacheManagerBuilderCustomizer myRedisCacheManagerBuilderCustomizer() {
return (builder) -> builder
.withCacheConfiguration("cache1", RedisCacheConfiguration
.defaultCacheConfig().entryTtl(Duration.ofSeconds(10)))
.withCacheConfiguration("cache2", RedisCacheConfiguration
.defaultCacheConfig().entryTtl(Duration.ofMinutes(1)));
}
}
import org.springframework.boot.cache.autoconfigure.RedisCacheManagerBuilderCustomizer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.cache.RedisCacheConfiguration
import java.time.Duration
@Configuration(proxyBeanMethods = false)
class MyRedisCacheManagerConfiguration {
@Bean
fun myRedisCacheManagerBuilderCustomizer(): RedisCacheManagerBuilderCustomizer {
return RedisCacheManagerBuilderCustomizer { builder ->
builder
.withCacheConfiguration(
"cache1", RedisCacheConfiguration
.defaultCacheConfig().entryTtl(Duration.ofSeconds(10))
)
.withCacheConfiguration(
"cache2", RedisCacheConfiguration
.defaultCacheConfig().entryTtl(Duration.ofMinutes(1))
)
}
}
}
Caffeine
Caffeine 是 Guava 缓存的 Java 8 重写,它取代了对 Guava 的支持。如果 Caffeine 存在,则会自动配置 CaffeineCacheManager(由 spring-boot-starter-cache 启动器提供)。可以通过设置 spring.cache.cache-names 属性在启动时创建缓存,并且可以通过以下方式(按所示顺序)进行自定义
-
由
spring.cache.caffeine.spec定义的缓存规范 -
定义了一个
CaffeineSpecbean -
定义了一个
Caffeinebean
例如,以下配置创建了 cache1 和 cache2 缓存,其最大大小为 500,存活时间 为 10 分钟
-
属性
-
YAML
spring.cache.cache-names=cache1,cache2
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s
spring:
cache:
cache-names: "cache1,cache2"
caffeine:
spec: "maximumSize=500,expireAfterAccess=600s"
如果定义了 CacheLoader bean,它会自动与 CaffeineCacheManager 关联。由于 CacheLoader 将与缓存管理器管理的所有缓存关联,因此它必须定义为 CacheLoader<Object, Object>。自动配置会忽略任何其他泛型类型。
Cache2k
Cache2k 是一个内存缓存。如果存在 Cache2k spring 集成,则会自动配置 SpringCache2kCacheManager。
可以通过设置 spring.cache.cache-names 属性在启动时创建缓存。缓存默认值可以通过 Cache2kBuilderCustomizer bean 进行自定义。以下示例显示了一个定制器,它将缓存容量配置为 200 个条目,过期时间为 5 分钟
-
Java
-
Kotlin
import java.util.concurrent.TimeUnit;
import org.springframework.boot.cache.autoconfigure.Cache2kBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class MyCache2kDefaultsConfiguration {
@Bean
public Cache2kBuilderCustomizer myCache2kDefaultsCustomizer() {
return (builder) -> builder.entryCapacity(200)
.expireAfterWrite(5, TimeUnit.MINUTES);
}
}
import org.springframework.boot.cache.autoconfigure.Cache2kBuilderCustomizer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.util.concurrent.TimeUnit
@Configuration(proxyBeanMethods = false)
class MyCache2kDefaultsConfiguration {
@Bean
fun myCache2kDefaultsCustomizer(): Cache2kBuilderCustomizer {
return Cache2kBuilderCustomizer { builder ->
builder.entryCapacity(200)
.expireAfterWrite(5, TimeUnit.MINUTES)
}
}
}
简单
如果找不到其他任何提供程序,则会配置一个使用 ConcurrentHashMap 作为缓存存储的简单实现。如果您的应用程序中没有缓存库,则这是默认设置。默认情况下,缓存会按需创建,但您可以通过设置 cache-names 属性来限制可用缓存列表。例如,如果您只想要 cache1 和 cache2 缓存,请按如下方式设置 cache-names 属性
-
属性
-
YAML
spring.cache.cache-names=cache1,cache2
spring:
cache:
cache-names: "cache1,cache2"
如果您这样做并且您的应用程序使用了未列出的缓存,那么它会在需要缓存时在运行时失败,而不是在启动时失败。这类似于“真实”缓存提供程序在使用未声明的缓存时的行为方式。
无
当您的配置中存在 @EnableCaching 时,也期望有一个合适的缓存配置。如果您有自定义的 org.springframework.cache.CacheManager,请考虑在单独的 @Configuration 类中定义它,以便在必要时可以覆盖它。None 使用无操作实现,这在测试中很有用,并且当 spring-boot-cache-test 模块存在时,切片测试默认通过 @AutoConfigureCache 使用它。
如果您需要在某个环境中而不是自动配置的缓存管理器中使用无操作缓存,请将缓存类型设置为 none,如以下示例所示
-
属性
-
YAML
spring.cache.type=none
spring:
cache:
type: "none"