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.