Azure APIM cache-lookup缓存连接失败的fallback处理方案咨询
针对Azure APIM内部缓存连接失败的处理方案
首先澄清核心误解:当内部缓存连接失败时,cache-lookup策略不会直接将null写入响应体,而是静默跳过缓存读取流程,让请求继续向后端服务发起调用。你当前的代码判断响应体是否为null,只能处理后端返回空值的场景,无法覆盖缓存连接失败的情况。
正确的处理逻辑
Azure APIM执行cache-lookup后,会在context.Variables中存入CacheLookupHit布尔变量:
true:缓存命中,直接返回缓存内容,终止后续流程false:缓存未命中(包括缓存连接失败导致的无法读取),请求继续向后端
如果你的业务需求是当缓存未命中(含连接失败)时触发兜底逻辑,可按以下方式调整策略:
<policies> <inbound> <base /> <cache-lookup vary-by-developer="false" vary-by-developer-groups="false" downstream-caching-type="none" caching-type="internal" /> <!-- 缓存未命中(含连接失败)时返回自定义错误 --> <choose> <when condition="@((bool)context.Variables["CacheLookupHit"] == false)"> <return-response> <set-status code="503" reason="Cache Unavailable" /> <set-body>{"error": "Failed to access cache, service temporarily unavailable"}</set-body> </return-response> </when> </choose> <!-- 仅缓存命中时才会执行后端服务调用 --> <set-backend-service base-url="https://run.mocky.io/v3/redacted" /> </inbound> <backend> <base /> </backend> <outbound> <base /> <cache-store duration="1800" /> </outbound> <on-error> <base /> </on-error> </policies>
模拟缓存异常的测试方法
APIM内部缓存无法直接模拟连接失败,可通过以下方式验证逻辑:
- 临时关闭APIM实例的内部缓存功能(在实例的「缓存」设置中禁用),此时
cache-lookup会始终返回CacheLookupHit=false,触发你设置的兜底逻辑 - 若要模拟
null返回场景,可临时改用cache-lookup-value策略测试:<inbound> <base /> <cache-lookup-value key="test-cache-key" variable-name="cachedData" caching-type="internal" /> <choose> <when condition="@(context.Variables["cachedData"] == null)"> <return-response> <set-status code="500" reason="Cache Error" /> <set-body>{"error": "Cache returned null value"}</set-body> </return-response> </when> </choose> </inbound>
现有代码的修正建议
如果你仅需处理「后端返回空响应」的场景,现有代码需修正解析空响应体时的异常问题:
<outbound> <base /> <set-variable name="originalResponseBody" value="@(context.Response.Body.Length > 0 ? context.Response.Body.As<JObject>(preserveContent: true) : null)" /> <choose> <when condition="@(context.Variables["originalResponseBody"] == null)"> <return-response> <set-status code="500" reason="Error" /> <set-body>{"error": "Empty or null response received"}</set-body> </return-response> </when> </choose> <cache-store duration="1800" /> </outbound>
内容的提问来源于stack exchange,提问作者Krusty
相关产品推荐
相关产品推荐

