API 管理缓存策略API Management caching policies

本主题提供以下 API 管理策略的参考。This topic provides a reference for the following API Management policies. 有关添加和配置策略的信息,请参阅 API 管理中的策略For information on adding and configuring policies, see Policies in API Management.

缓存策略Caching policies

从缓存中获取Get from cache

使用 cache-lookup 策略执行缓存查找,并返回有效的缓存响应(如果有)。Use the cache-lookup policy to perform cache look up and return a valid cached response when available. 当响应内容在某个时间段内保持静态时,即可应用该策略。This policy can be applied in cases where response content remains static over a period of time. 响应缓存可以降低后端 Web 服务器需要满足的带宽和处理能力要求,并可以减小 API 使用者能够察觉到的延迟。Response caching reduces bandwidth and processing requirements imposed on the backend web server and lowers latency perceived by API consumers.

备注

此策略必须已设置相应的存储到缓存策略。This policy must have a corresponding Store to cache policy.

策略语句Policy statement

<cache-lookup vary-by-developer="true | false" vary-by-developer-groups="true | false" caching-type="prefer-external | external | internal" downstream-caching-type="none | private | public" must-revalidate="true | false" allow-private-response-caching="@(expression to evaluate)">
  <vary-by-header>Accept</vary-by-header>  
  <!-- should be present in most cases -->  
  <vary-by-header>Accept-Charset</vary-by-header>  
  <!-- should be present in most cases -->  
  <vary-by-header>Authorization</vary-by-header>  
  <!-- should be present when allow-private-response-caching is "true"-->  
  <vary-by-header>header name</vary-by-header>  
  <!-- optional, can repeated several times -->  
  <vary-by-query-parameter>parameter name</vary-by-query-parameter>  
  <!-- optional, can repeated several times -->  
</cache-lookup>  

示例Examples

示例Example

<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>  

策略表达式使用示例Example using policy expressions

此示例演示如何配置 API 管理响应缓存持续时间,使之匹配由后端服务的 Cache-Control 指令指定的后端服务响应缓存。This example shows how to configure API Management response caching duration that matches the response caching of the backend service as specified by the backed service's Cache-Control directive.

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

有关详细信息,请参阅策略表达式上下文变量For more information, see Policy expressions and Context variable.

元素Elements

名称Name 说明Description 必选Required
cache-lookupcache-lookup 根元素。Root element. Yes
vary-by-headervary-by-header 开始按指定标头(例如 Accept、Accept-Charset、Accept-Encoding、Accept-Language、Authorization、Expect、From、Host、If-Match)的值缓存响应。Start caching responses per value of specified header, such as Accept, Accept-Charset, Accept-Encoding, Accept-Language, Authorization, Expect, From, Host, If-Match. No
vary-by-query-parametervary-by-query-parameter 根据指定查询参数的值开始缓存响应。Start caching responses per value of specified query parameters. 请输入一个或多个参数。Enter a single or multiple parameters. 使用分号作为分隔符。Use semicolon as a separator. 如果未指定任何参数,将使用所有查询参数。If none are specified, all query parameters are used. No

属性Attributes

名称Name 说明Description 必选Required 默认Default
allow-private-response-cachingallow-private-response-caching 设置为 true 即可缓存包含 Authorization 标头的请求。When set to true, allows caching of requests that contain an Authorization header. No falsefalse
caching-typecaching-type 在以下属性值之间进行选择:Choose between the following values of the attribute:
- internal 使用内置的 API 管理缓存;- internal to use the built-in API Management cache,
- prefer-external 如果外部缓存已配置,则使用外部缓存,否则使用内部缓存。- prefer-external to use external cache if configured or internal cache otherwise.
No prefer-external
downstream-caching-typedownstream-caching-type 此属性必须设置为以下值之一。This attribute must be set to one of the following values.

- none - 不允许下游缓存。- none - downstream caching is not allowed.
- private - 允许下游专用缓存。- private - downstream private caching is allowed.
- public - 允许专用和共享下游缓存。- public - private and shared downstream caching is allowed.
No nonenone
must-revalidatemust-revalidate 启用下游缓存时,此属性会启用或关闭网关响应中的 must-revalidate 缓存控制指令。When downstream caching is enabled this attribute turns on or off the must-revalidate cache control directive in gateway responses. No truetrue
vary-by-developervary-by-developer 设置为 true 即可按订阅密钥缓存响应。Set to true to cache responses per subscription key. Yes
vary-by-developer-groupsvary-by-developer-groups 设置为 true 即可按用户组缓存响应。Set to true to cache responses per user group. Yes

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略段: 入站Policy sections: inbound
  • 策略范围: 所有范围Policy scopes: all scopes

存储到缓存Store to cache

cache-store 策略根据指定的缓存设置缓存响应。The cache-store policy caches responses according to the specified cache settings. 当响应内容在某个时间段内保持静态时,即可应用该策略。This policy can be applied in cases where response content remains static over a period of time. 响应缓存可以降低后端 Web 服务器需要满足的带宽和处理能力要求,并可以减小 API 使用者能够察觉到的延迟。Response caching reduces bandwidth and processing requirements imposed on the backend web server and lowers latency perceived by API consumers.

备注

此策略必须已设置相应的从缓存中获取策略。This policy must have a corresponding Get from cache policy.

策略语句Policy statement

<cache-store duration="seconds" />  

示例Examples

示例Example

<policies>  
    <inbound>  
        <base />  
          <cache-lookup vary-by-developer="true | false" vary-by-developer-groups="true | false" downstream-caching-type="none | private | public" must-revalidate="true | false">  
                <vary-by-query-parameter>parameter name</vary-by-query-parameter> <!-- optional, can repeated several times -->  
        </cache-lookup>  
    </inbound>  
    <outbound>  
        <base />  
            <cache-store duration="3600" />  
    </outbound>  
</policies>  

策略表达式使用示例Example using policy expressions

此示例演示如何配置 API 管理响应缓存持续时间,使之匹配由后端服务的 Cache-Control 指令指定的后端服务响应缓存。This example shows how to configure API Management response caching duration that matches the response caching of the backend service as specified by the backed service's Cache-Control directive.

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

有关详细信息,请参阅策略表达式上下文变量For more information, see Policy expressions and Context variable.

元素Elements

名称Name 说明Description 必选Required
cache-storecache-store 根元素。Root element. Yes

属性Attributes

名称Name 说明Description 必选Required 默认Default
durationduration 缓存条目的生存时间,以秒为单位指定。Time-to-live of the cached entries, specified in seconds. Yes 空值N/A

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略段: 出站Policy sections: outbound
  • 策略范围: 所有范围Policy scopes: all scopes

从缓存中获取值Get value from cache

使用 cache-lookup-value 策略,可以通过密钥执行缓存查找,并返回缓存的值。Use the cache-lookup-value policy to perform cache lookup by key and return a cached value. 密钥的值可以是任意字符串,通常使用策略表达式来提供密钥。The key can have an arbitrary string value and is typically provided using a policy expression.

备注

此策略必须已设置相应的在缓存中存储值策略。This policy must have a corresponding Store value in cache policy.

策略语句Policy statement

<cache-lookup-value key="cache key value"   
    default-value="value to use if cache lookup resulted in a miss"   
    variable-name="name of a variable looked up value is assigned to"
    caching-type="prefer-external | external | internal" />

示例Example

有关此策略的详细信息和示例,请参阅 Azure API 管理中的自定义缓存For more information and examples of this policy, see Custom caching in Azure API Management.

<cache-lookup-value  
    key="@("userprofile-" + context.Variables["enduserid"])"    
    variable-name="userprofile" />  
  

元素Elements

名称Name 说明Description 必选Required
cache-lookup-valuecache-lookup-value 根元素。Root element. Yes

属性Attributes

名称Name 说明Description 必选Required 默认Default
default-valuedefault-value 在缓存密钥查找未命中的情况下,会分配给变量的值。A value that will be assigned to the variable if the cache key lookup resulted in a miss. 如果未指定此属性,则会分 nullIf this attribute is not specified, null is assigned. No null
keykey 要在查找中使用的缓存密钥值。Cache key value to use in the lookup. Yes 空值N/A
variable-namevariable-name 在查找成功的情况下,会向其分配查找值的上下文变量的名称。Name of the context variable the looked up value will be assigned to, if lookup is successful. 如果查找未命中,则会为此变量分配 default-value 属性的值或 null(如果省略了 default-value 属性)。If lookup results in a miss, the variable will be assigned the value of the default-value attribute or null, if the default-value attribute is omitted. Yes 空值N/A

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站、出站、后端、错误时Policy sections: inbound, outbound, backend, on-error
  • 策略范围: 所有范围Policy scopes: all scopes

在缓存中存储值Store value in cache

cache-store-value 按密钥执行缓存存储。The cache-store-value performs cache storage by key. 密钥的值可以是任意字符串,通常使用策略表达式来提供密钥。The key can have an arbitrary string value and is typically provided using a policy expression.

备注

此策略必须已设置相应的从缓存中获取值策略。This policy must have a corresponding Get value from cache policy.

策略语句Policy statement

<cache-store-value key="cache key value" value="value to cache" duration="seconds" caching-type="prefer-external | external | internal" />

示例Example

有关此策略的详细信息和示例,请参阅 Azure API 管理中的自定义缓存For more information and examples of this policy, see Custom caching in Azure API Management.

<cache-store-value  
    key="@("userprofile-" + context.Variables["enduserid"])"  
    value="@((string)context.Variables["userprofile"])" duration="100000" />  
  

元素Elements

名称Name 说明Description 必选Required
cache-store-valuecache-store-value 根元素。Root element. Yes

属性Attributes

名称Name 说明Description 必选Required 默认Default
caching-typecaching-type 在以下属性值之间进行选择:Choose between the following values of the attribute:
- internal 使用内置的 API 管理缓存;- internal to use the built-in API Management cache,
- prefer-external 如果外部缓存已配置,则使用外部缓存,否则使用内部缓存。- prefer-external to use external cache if configured or internal cache otherwise.
No prefer-external
durationduration 会根据提供的期间值(以秒为单位指定)将值缓存一段时间。Value will be cached for the provided duration value, specified in seconds. Yes 空值N/A
keykey 缓存密钥,会在其下存储值。Cache key the value will be stored under. Yes 空值N/A
value 要缓存的值。The value to be cached. Yes 空值N/A

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站、出站、后端、错误时Policy sections: inbound, outbound, backend, on-error

  • 策略范围: 所有范围Policy scopes: all scopes

从缓存中删除值Remove value from cache

cache-remove-value 删除通过密钥标识的缓存项。The cache-remove-value deletes a cached item identified by its key. 密钥的值可以是任意字符串,通常使用策略表达式来提供密钥。The key can have an arbitrary string value and is typically provided using a policy expression.

策略语句Policy statement

  
<cache-remove-value key="cache key value" caching-type="prefer-external | external | internal"  />
  

示例Example

  
<cache-remove-value key="@("userprofile-" + context.Variables["enduserid"])"/>  
  

元素Elements

名称Name 说明Description 必选Required
cache-remove-valuecache-remove-value 根元素。Root element. Yes

属性Attributes

名称Name 说明Description 必选Required 默认Default
caching-typecaching-type 在以下属性值之间进行选择:Choose between the following values of the attribute:
- internal 使用内置的 API 管理缓存;- internal to use the built-in API Management cache,
- prefer-external 如果外部缓存已配置,则使用外部缓存,否则使用内部缓存。- prefer-external to use external cache if configured or internal cache otherwise.
No prefer-external
keykey 以前所缓存的值(将从缓存中删除)的密钥。The key of the previously cached value to be removed from the cache. Yes 空值N/A

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes .

  • 策略节: 入站、出站、后端、错误时Policy sections: inbound, outbound, backend, on-error
  • 策略范围: 所有范围Policy scopes: all scopes

后续步骤Next steps

有关如何使用策略的详细信息,请参阅:For more information working with policies, see: