建立進階原則

已完成

本單元提供下列 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/> 元素內所括住的原則陳述式。 如果所有 <when/> 元素的條件屬性都是 false,則會套用 <otherwise/> 元素內所括住的原則 (如果有的話)。

轉寄要求

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>

其他資源