LocalResponseCache GatewayFilter 工厂

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

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

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

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

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

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

它接受第一个参数来覆盖缓存条目的过期时间(用 s 表示秒,m 表示分钟,h 表示小时),并接受第二个参数来设置此路由的缓存最大大小以驱逐条目(KBMBGB)。

以下列表显示了如何添加本地响应缓存 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();
}

或此

application.yaml
spring:
  cloud:
    gateway:
      routes:
      - id: resource
        uri: https://:9000
        predicates:
        - Path=/resource
        filters:
        - LocalResponseCache=30m,500MB
此过滤器还会自动计算 HTTP Cache-Control 头部中的 max-age 值。仅当原始响应中存在 max-age 时,该值才会被 timeToLive 配置参数中设置的秒数重写。在后续调用中,此值会根据响应过期前剩余的秒数重新计算。
要启用此功能,请添加 com.github.ben-manes.caffeine:caffeinespring-boot-starter-cache 作为项目依赖项。
如果您的项目创建了自定义的 CacheManager bean,则需要使用 @Primary 进行标记或使用 @Qualifier 进行注入。
© . This site is unofficial and not affiliated with VMware.