创建高级策略
本单元提供了以下 API 管理策略的参考信息:
- 控制流 - 根据布尔表达式的求值结果,有条件地应用策略语句。
- 转发请求 - 将请求转发到后端服务。
- 限制并发 - 阻止括住的策略一次执行超过指定数量的请求。
- 记录到事件中心 - 将指定格式的消息发送到记录器实体定义的事件中心。
- 模拟响应 - 中止管道执行,将模拟的响应直接返回给调用方。
- 重试 - 重试执行括住的策略语句,直到符合条件为止。 执行将按指定的时间间隔重复,最多执行到指定的重试计数。
控制流
choose
策略根据布尔表达式的计算结果来应用所包括的策略语句,类似于编程语言中的 if-then-else 或开关构造。
<choose>
<when condition="Boolean expression | Boolean constant">
<!— one or more policy statements to be applied if the above condition is true -->
</when>
<when condition="Boolean expression | Boolean constant">
<!— one or more policy statements to be applied if the above condition is true -->
</when>
<otherwise>
<!— one or more policy statements to be applied if none of the above conditions are true -->
</otherwise>
</choose>
控制流策略必须包含至少一个 <when/>
元素。
<otherwise/>
元素是可选的。
<when/>
元素中的条件根据其在策略中的出现顺序求值。 条件属性为 true 时,将会应用包含在第一个 <when/>
元素内的策略语句。 如果 <otherwise/>
元素的所有条件属性都为 false,则将应用包含在 <when/>
元素中的策略(如果存在)。
转发请求
forward-request
策略将传入请求转发到请求上下文中指定的后端服务。 后端服务 URL 在 API 设置中指定,可以使用设置后端服务策略进行更改。
删除此策略会导致请求不会转发到后端服务。 成功完成入站部分中的策略后,将立即评估出站部分中的策略。
<forward-request timeout="time in seconds" follow-redirects="true | false"/>
限制并发
limit-concurrency
策略阻止括住的策略在任意时间执行超过指定数量的请求。 请求超过指定数量后,新请求将立即失败,并显示“429 请求过多”状态代码。
<limit-concurrency key="expression" max-count="number">
<!— nested policy statements -->
</limit-concurrency>
记录到事件中心
log-to-eventhub
策略将指定格式的消息发送到记录器实体定义的事件中心。 从名称可以看出,此策略用于保存所选请求或响应上下文信息,以便进行联机或脱机分析。
<log-to-eventhub logger-id="id of the logger entity" partition-id="index of the partition where messages are sent" partition-key="value used for partition assignment">
Expression returning a string to be logged
</log-to-eventhub>
模拟响应
正如其名所示,mock-response
用于模拟 API 和操作。 它会中止正常的管道执行,并将模拟的响应返回给调用方。 该策略始终尝试返回保真度最高的响应。 它首选响应内容示例(若可用)。 如果提供架构而不提供示例,它将根据架构生成示例响应。 如果找不到示例或架构,则返回没有任何内容的响应。
<mock-response status-code="code" content-type="media type"/>
重试
retry
策略会执行其子策略一次,并重新尝试执行,直至重试 condition
变为 false
,或者重试 count
为零。
<retry
condition="boolean expression or literal"
count="number of retry attempts"
interval="retry interval in seconds"
max-interval="maximum retry interval in seconds"
delta="retry interval delta in seconds"
first-fast-retry="boolean expression or literal">
<!-- One or more child policies. No restrictions -->
</retry>
返回响应
return-response
策略会中止管道执行,为调用方返回默认响应或自定义响应。 默认响应为200 OK
,无正文。 可以通过上下文变量或策略语句指定自定义响应。 当两者都提供时,策略语句会在返回到调用方之前修改上下文变量。
<return-response response-variable-name="existing context variable">
<set-header/>
<set-body/>
<set-status/>
</return-response>
其他资源
- 有关更多策略示例,请访问 API 管理策略。
- API 管理策略中的错误处理