Azure API Management:判断cache-lookup成功及获取缓存键方法
解决方案
一、仅在缓存未命中时设置cacheInProgress变量
Azure API Management中,cache-lookup命中缓存时会直接返回缓存响应,不会继续执行后续入站策略,也不会转发请求到后端。利用这个特性,我们可以通过<choose>策略控制cache-store-value仅在缓存未命中时执行,避免不必要的并发限制。
二、使用APIM自动生成的缓存键替代手动拼接
APIM会根据cache-lookup的配置(如vary-by-header等)自动生成缓存键,可通过context.Request.CacheKey直接获取,无需手动拼接请求参数和头信息。
修改后的完整策略代码
<inbound> <base /> <!-- 使用APIM自动生成的缓存键作为cacheInProgressKey --> <set-variable name="cacheInProgressKey" value="@(context.Request.CacheKey)" /> <cache-lookup-value key="@(context.Variables["cacheInProgressKey"] as string)" variable-name="cacheInProgressValue" /> <retry condition="@(context.Variables.GetValueOrDefault("cacheInProgressValue", "false") != "false")" count="5" interval="1" first-fast-retry="false"> <set-variable name="cacheInProgressValue" value="false" /> <cache-lookup-value key="@(context.Variables["cacheInProgressKey"] as string)" variable-name="cacheInProgressValue" /> </retry> <cache-lookup vary-by-developer="false" vary-by-developer-groups="false" allow-private-response-caching="true" downstream-caching-type="none"> <vary-by-header>Accept</vary-by-header> <vary-by-header>Accept-Charset</vary-by-header> </cache-lookup> <!-- 仅在缓存未命中时设置cacheInProgress标记 --> <choose> <when condition="@(context.Response == null || context.Response.StatusCode == 0)"> <cache-store-value key="@(context.Variables["cacheInProgressKey"] as string)" value="true" duration="5" /> </when> </choose> </inbound> <backend> <base /> </backend> <outbound> <base /> <cache-remove-value key="@(context.Variables["cacheInProgressKey"] as string)" /> <cache-store duration="60" /> </outbound>
关键修改说明
缓存键生成优化:
- 用
context.Request.CacheKey替代手动拼接的URL+头信息,该值完全匹配cache-lookup使用的内部缓存键,避免因手动拼接不一致导致的问题。
- 用
条件执行cache-store-value:
- 通过
<choose>策略判断context.Response是否为空或状态码为0(缓存命中时APIM会立即填充响应对象),仅在缓存未命中时执行cache-store-value,减少不必要的缓存写入,提升并发能力。
- 通过
原有重试逻辑保留:
- 保留了请求排队等待缓存生成完成的重试逻辑,确保同一资源的并发请求不会重复触发后端调用。
内容的提问来源于stack exchange,提问作者Will
相关产品推荐
相关产品推荐

