添加缓存以提高 Azure API 管理中的性能Add caching to improve performance in Azure API Management

API 管理中的操作可以配置为响应缓存。Operations in API Management can be configured for response caching. 响应缓存可以显著减少 API 延迟、带宽消耗和不经常更改数据的 web 服务负载。Response caching can significantly reduce API latency, bandwidth consumption, and web service load for data that does not change frequently.

若要更详细地了解缓存,请参阅 API 管理缓存策略Azure API 管理中的自定义缓存For more detailed information about caching, see API Management caching policies and Custom caching in Azure API Management.

缓存策略

学习内容:What you'll learn:

  • 为 API 添加响应缓存Add response caching for your API
  • 验证作用的缓存Verify caching in action

先决条件Prerequisites

完成本教程:To complete this tutorial:

添加缓存策略 Add the caching policies

使用此示例中显示的缓存策略时,向 GetSpeakers 操作发出的第一个请求返回来自后端服务的响应。With caching policies shown in this example, the first request to the GetSpeakers operation returns a response from the backend service. 将缓存此响应,由指定的标头和查询字符串参数进行键控。This response is cached, keyed by the specified headers and query string parameters. 采用匹配的参数,对操作的后续调用会返回缓存的响应,直到缓存时间间隔过期。Subsequent calls to the operation, with matching parameters, will have the cached response returned, until the cache duration interval has expired.

  1. https://portal.azure.cn 中登录 Azure 门户。Sign in to the Azure portal at https://portal.azure.cn.

  2. 浏览到自己的 APIM 实例。Browse to your APIM instance.

  3. 选择“API”选项卡。Select the APIs tab.

  4. 在 API 列表中单击“演示会议 API”。Click Demo Conference API from your API list.

  5. 选择“GetSpeakers”。Select GetSpeakers.

  6. 选择屏幕顶部的“设计”选项卡。On the top of the screen, select Design tab.

  7. 在“入站处理”部分中,单击 </> 图标。In the Inbound processing section, click the </> icon.

    代码编辑器

  8. inbound 元素中添加以下策略:In the inbound element, add the following policy:

     <cache-lookup vary-by-developer="false" vary-by-developer-groups="false">
         <vary-by-header>Accept</vary-by-header>
         <vary-by-header>Accept-Charset</vary-by-header>
         <vary-by-header>Authorization</vary-by-header>
     </cache-lookup>
    
  9. outbound 元素中添加以下策略:In the outbound element, add the following policy:

    <cache-store caching-mode="cache-on" duration="20" />
    

    持续时间 指定缓存响应的过期时间间隔。Duration specifies the expiration interval of the cached responses. 此示例中的时间间隔为 20 秒。In this example, the interval is 20 seconds.

调用操作和测试缓存 Call an operation and test the caching

若要查看作用的缓存,请从开发人员门户调用操作。To see the caching in action, call the operation from the developer portal.

  1. 在 Azure 门户中浏览到自己的 APIM 实例。In the Azure portal, browse to your APIM instance.
  2. 选择“API”选项卡。Select the APIs tab.
  3. 选择向其添加了缓存策略的 API。Select the API to which you added caching policies.
  4. 选择“GetSpeakers”操作。Select the GetSpeakers operation.
  5. 单击右上方菜单中的“测试”选项卡。Click the Test tab in the top right menu.
  6. 按“发送”。Press Send.

后续步骤 Next steps