存储到缓存

cache-store 策略根据指定的缓存设置缓存响应。 当响应内容在某个时间段内保持静态时,即可应用该策略。 响应缓存可以降低后端 Web 服务器需要满足的带宽和处理能力要求,并可以减小 API 使用者能够察觉到的延迟。

注意

此策略必须已设置相应的从缓存中获取策略。

重要

内置缓存是易失性的,由同一 API 管理服务中同一区域的所有单元共享。

提示

为了帮助你配置此策略,门户提供了基于窗体的引导式编辑器。 详细了解如何设置或编辑 API 管理策略

策略语句

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

属性

属性 说明 需要 默认
duration 缓存条目的生存时间,以秒为单位指定。 允许使用策略表达式。 空值
cache-response 设置为 true 可缓存当前 HTTP 响应。 如果省略此属性,则只缓存状态代码为 200 OK 的 HTTP 响应。 允许使用策略表达式。 false

使用情况

使用注意事项

  • API 管理仅缓存对 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-store 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-store>

<!-- 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;
  }" />

有关详细信息,请参阅策略表达式上下文变量

后续步骤

有关使用策略的详细信息,请参阅: