跳到主要内容
版本:5.0.1

LocalResponseCache GatewayFilter 工厂

DeepSeek V3 中英对照 LocalResponseCache GatewayFilter Factory LocalResponseCache GatewayFilter Factory

此过滤器允许缓存响应体和标头,遵循以下规则:

  • 它只能缓存无请求体的 GET 请求。

  • 它仅对以下状态码之一缓存响应:HTTP 200(OK)、HTTP 206(Partial Content)或 HTTP 301(Moved Permanently)。

  • 如果 Cache-Control 标头不允许缓存(请求中存在 no-store 或响应中存在 no-store 或 private),则不会缓存响应数据。

  • 如果响应已被缓存,并且使用 Cache-Control 标头中的 no-cache 值执行新请求,它将返回一个无响应体的 304(Not Modified)响应。

此过滤器按路由配置本地响应缓存,仅在启用 spring.cloud.gateway.filter.local-response-cache.enabled 属性时可用。此外,全局配置的本地响应缓存 也可作为一项功能使用。

它接受第一个参数来覆盖缓存条目的过期时间(以 s 表示秒,m 表示分钟,h 表示小时),以及第二个参数来设置为此路由驱逐缓存条目的最大容量(KB、MB 或 GB)。

以下清单展示了如何添加本地响应缓存 GatewayFilter:

@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("rewrite_response_upper", r -> r.host("*.rewriteresponseupper.org")
.filters(f -> f.prefixPath("/httpbin")
.localResponseCache(Duration.ofMinutes(30), "500MB")
).uri(uri))
.build();
}

或者这个

spring:
cloud:
gateway:
routes:
- id: resource
uri: http://localhost:9000
predicates:
- Path=/resource
filters:
- LocalResponseCache=30m,500MB
备注

此过滤器还会自动计算 HTTP Cache-Control 头中的 max-age 值。只有当原始响应中存在 max-age 时,该值才会被重写为 timeToLive 配置参数中设置的秒数。在后续调用中,此值会根据响应过期前的剩余秒数重新计算。

备注

要启用此功能,请将 com.github.ben-manes.caffeine:caffeine 和 spring-boot-starter-cache 添加为项目依赖。

注意

如果你的项目创建了自定义的 CacheManager bean,则需要使用 @Primary 进行标记,或者通过 @Qualifier 进行注入。