此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Boot 3.4.0! |
缓存
Spring Framework 支持以透明方式向应用程序添加缓存。
抽象的核心是将缓存应用于方法,从而根据缓存中可用的信息减少执行次数。
缓存逻辑以透明方式应用,不会对调用程序造成任何干扰。
Spring Boot 会自动配置缓存基础设施,只要使用@EnableCaching
注解。
有关更多详细信息,请查看 Spring Framework 参考的相关部分。 |
简而言之,要将缓存添加到服务的作中,请将相关 Comments 添加到其方法中,如以下示例所示:
-
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
cache 匹配precision
论点。
如果找到条目,则缓存中的内容会立即返回给调用方,并且不会调用该方法。
否则,将调用该方法,并在返回值之前更新缓存。
您还可以使用标准 JSR-107 (JCache) 注释(例如@CacheResult ) 透明地显示。
但是,我们强烈建议您不要混合和匹配 Spring Cache 和 JCache 注释。 |
如果不添加任何特定的缓存库, Spring Boot 会自动配置一个简单的提供程序,该提供程序在内存中使用并发映射。
当需要缓存时(例如piDecimals
在前面的示例中),此提供程序会为您创建它。
简单提供程序并不真正推荐用于生产用途,但它非常适合入门并确保您了解这些功能。
当您决定要使用的缓存提供程序时,请务必阅读其文档以了解如何配置应用程序使用的缓存。
几乎所有提供程序都要求您显式配置在应用程序中使用的每个缓存。
有些提供了自定义由spring.cache.cache-names
财产。
支持的缓存提供程序
缓存抽象不提供实际的存储,并且依赖于由Cache
和CacheManager
接口。
如果您尚未定义CacheManager
或CacheResolver
叫cacheResolver
(参见CachingConfigurer
),Spring Boot 会尝试检测以下提供程序(按指示的顺序):
-
JCache (JSR-107)(EhCache 3、Hazelcast、Infinispan 等)
如果CacheManager 由 Spring Boot 自动配置,则可以通过将spring.cache.type 财产。
如果需要在某些环境(例如测试)中使用无作缓存,请使用此属性。 |
使用spring-boot-starter-cache Starter 快速添加基本缓存依赖项。
首发球员带来spring-context-support .
如果手动添加依赖项,则必须包含spring-context-support 以使用 JCache 或 Caffeine 支持。 |
如果CacheManager
由 Spring Boot 自动配置,则可以通过公开实现CacheManagerCustomizer
接口。
下面的示例设置一个标志来表示null
值不应向下传递到底层 Map:
-
Java
-
Kotlin
import org.springframework.boot.autoconfigure.cache.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.autoconfigure.cache.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
豆。
一个CacheManager
将创建该类型的所有 Wrapping 。
JCache (JSR-107)
JCache 是通过存在CachingProvider
在类路径上(即,类路径上存在符合 JSR-107 的缓存库),并且JCacheCacheManager
由spring-boot-starter-cache
起动机。
可以使用各种兼容的库,并且 Spring Boot 为 Ehcache 3、Hazelcast 和 Infinispan 提供依赖项管理。
也可以添加任何其他兼容的库。
可能会存在多个提供程序,在这种情况下,必须显式指定提供程序。 即使 JSR-107 标准没有强制执行定义配置文件位置的标准化方法, Spring Boot 也会尽力适应使用实现细节设置缓存,如以下示例所示:
-
Properties
-
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 可用,它会自动重新用于CacheManager 以及,除非spring.cache.jcache.config 属性。 |
有两种方法可以自定义底层CacheManager
:
-
可以在启动时通过设置
spring.cache.cache-names
财产。 如果自定义Configuration
bean 的定义,则用于自定义它们。 -
JCacheManagerCustomizer
bean 是使用CacheManager
进行完全自定义。
如果标准的CacheManager bean 时,它会自动包装在CacheManager 抽象期望的实现。
不会对其应用进一步的自定义。 |
Hazelcast
Spring Boot 具有对 Hazelcast 的一般支持。
如果HazelcastInstance
已自动配置并且com.hazelcast:hazelcast-spring
位于 Classpath 上,它会自动包装在CacheManager
.
Hazelcast 可以用作符合 JCache 的缓存或用作 SpringCacheManager compliant 缓存。
设置spring.cache.type 自hazelcast ,Spring Boot 将使用CacheManager 基于实施。
如果要将 Hazelcast 用作符合 JCache 的缓存,请将spring.cache.type 自jcache .
如果您有多个符合 JCache 的缓存提供程序并希望强制使用 Hazelcast,则必须显式设置 JCache 提供程序。 |
Infinispan 无限
Infinispan 没有默认的配置文件位置,因此必须显式指定它。 否则,将使用默认引导程序。
-
Properties
-
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
必须使用 modules。
对于每个具有-jakarta
variant 中,必须使用 variant 代替 standard 模块。
例如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 分钟的缓存:
-
Properties
-
YAML
spring.cache.cache-names=cache1,cache2
spring.cache.couchbase.expiration=10m
spring:
cache:
cache-names: "cache1,cache2"
couchbase:
expiration: "10m"
如果您需要对配置进行更多控制,请考虑注册CouchbaseCacheManagerBuilderCustomizer
豆。
以下示例显示了一个定制器,该定制器为cache1
和cache2
:
-
Java
-
Kotlin
import java.time.Duration;
import org.springframework.boot.autoconfigure.cache.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.autoconfigure.cache.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 分钟的缓存:
-
Properties
-
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
豆。
以下示例显示了一个定制器,该定制器配置了特定的生存时间cache1
和cache2
:
-
Java
-
Kotlin
import java.time.Duration;
import org.springframework.boot.autoconfigure.cache.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.autoconfigure.cache.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 是 Guava 缓存的 Java 8 重写,它取代了对 Guava 的支持。
如果存在咖啡因,则CaffeineCacheManager
(由spring-boot-starter-cache
starter) 是自动配置的。
可以在启动时通过设置spring.cache.cache-names
属性,并且可以由以下选项之一(按指示的顺序)进行自定义:
-
由
spring.cache.caffeine.spec
-
一个
CaffeineSpec
bean 定义 -
一个
Caffeine
bean 定义
例如,以下配置创建cache1
和cache2
最大大小为 500 且生存时间为 10 分钟的缓存
-
Properties
-
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>
.
auto-configuration 会忽略任何其他泛型类型。
缓存2k
Cache2k 是内存中的缓存。
如果存在 Cache2k Spring 集成,则SpringCache2kCacheManager
是自动配置的。
可以在启动时通过设置spring.cache.cache-names
财产。
缓存默认值可以使用Cache2kBuilderCustomizer
豆。
以下示例显示了一个定制器,该定制器将缓存的容量配置为 200 个条目,过期时间为 5 分钟:
-
Java
-
Kotlin
import java.util.concurrent.TimeUnit;
import org.springframework.boot.autoconfigure.cache.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.autoconfigure.cache.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
caches,将cache-names
属性,如下所示:
-
Properties
-
YAML
spring.cache.cache-names=cache1,cache2
spring:
cache:
cache-names: "cache1,cache2"
如果您这样做,并且您的应用程序使用未列出的缓存,则它会在运行时需要缓存时失败,但在启动时不会失败。 这类似于使用未声明的缓存时“真实”缓存提供程序的行为方式。
没有
什么时候@EnableCaching
,则还需要合适的缓存配置。
如果你有一个自定义的 ' org.springframework.cache.CacheManager' ,请考虑在单独的@Configuration
类,以便您可以根据需要覆盖它。
None 使用在测试中有用的 no-op 实现,而 slice 测试默认通过@AutoConfigureCache
.
如果需要在特定环境中使用 no-op 缓存而不是自动配置的缓存管理器,请将缓存类型设置为none
,如以下示例所示:
-
Properties
-
YAML
spring.cache.type=none
spring:
cache:
type: "none"