儲存至快取

適用於:所有 API 管理 層

cache-store 原則會根據指定的快取設定來快取回應。 此原則可於回應內容在一段期間維持靜態時套用。 回應快取可降低加諸於後端 Web 伺服器的頻寬和處理需求,並縮短 API 取用者所感受的延遲時間。

注意

此原則必須有對應的從快取中取得原則。

重要

內建快取具揮發性,且相同區域的所有單位共用相同的 API 管理服務。

注意

請依照原則陳述式中提供的順序,來設定原則的元素和子元素。 為了協助您設定此原則,入口網站會提供引導式表單型編輯器。 深入了解如何設定或編輯 APIM 原則

原則陳述式

<cache-store duration="seconds" cache-response="true | false" />

屬性

屬性 描述 是必要欄位 預設
duration 快取項目的存留時間,以秒為單位進行指定。 允許使用原則運算式。 Yes N/A
cache-response 設定為 true 以快取目前的 HTTP 回應。 如果省略屬性,就只會快取狀態碼為 200 OK 的 HTTP 回應。 允許使用原則運算式。 No false

使用方式

使用注意事項

  • APIM 只會快取對 HTTP GET 要求的回應。
  • 此原則只能在原則區段中使用一次。

範例

對應 cache-lookup 原則的範例

<policies>
    <inbound>
        <base />
        <cache-lookup vary-by-developer="false" vary-by-developer-groups="false" downstream-caching-type="none" must-revalidate="true" caching-type="internal" >
            <vary-by-query-parameter>version</vary-by-query-parameter>
        </cache-lookup>
    </inbound>
    <outbound>
        <cache-store duration="seconds" />
        <base />
    </outbound>
</policies>

使用原則運算式的範例

此範例說明如何設定 API 管理回應快取期間,使其符合備用服務之 Cache-Control 指示詞所指定的後端服務回應快取。

<!-- The following cache policy snippets demonstrate how to control API Management response cache duration with Cache-Control headers sent by the backend service. -->

<!-- Copy this snippet into the inbound section -->
<cache-lookup vary-by-developer="false" vary-by-developer-groups="false" downstream-caching-type="public" must-revalidate="true" >
  <vary-by-header>Accept</vary-by-header>
  <vary-by-header>Accept-Charset</vary-by-header>
</cache-lookup>

<!-- Copy this snippet into the outbound section. Note that cache duration is set to the max-age value provided in the Cache-Control header received from the backend service or to the default value of 5 min if none is found  -->
<cache-store duration="@{
    var header = context.Response.Headers.GetValueOrDefault("Cache-Control","");
    var maxAge = Regex.Match(header, @"max-age=(?<maxAge>\d+)").Groups["maxAge"]?.Value;
    return (!string.IsNullOrEmpty(maxAge))?int.Parse(maxAge):300;
  }"
 />

如需詳細資訊,請參閱原則運算式內容變數

如需使用原則的詳細資訊,請參閱: