服務呼叫政策

查看 Apigee Edge 說明文件。
前往 Apigee X說明文件
資訊

結果

服務呼叫政策可讓您從 API Proxy 流程呼叫其他服務。個人中心 可以呼叫外部服務 (例如符合 REST 樣式的外部服務端點) 內部服務 (例如相同機構和環境中的 API Proxy)。

  • 如果是外部用途,則呼叫的是 Proxy 上。系統會剖析第三方 API 回應,並插入您的 API 回應中 訊息、豐富及「混搭」應用程式使用者的資料你也可以請求 在要求流程中使用服務呼叫政策,然後在回應中傳遞資訊 指向 API Proxy 的 TargetEndpoint。
  • 在其他用途中,您呼叫的 Proxy 位於機構和環境中 與來電者聯絡例如,如果您的 Proxy 提供一些獨立的低階功能,可供一或多個 Proxy 使用。適用對象 例如,使用後端資料儲存庫公開建立/讀取/更新/刪除作業的 Proxy 可能為其他多個 Proxy (向用戶端公開資料) 的目標 Proxy。

這項政策支援透過 HTTP 和 HTTPS 提出的要求。

範例

<LocalTargetConnection>
    <APIProxy>data-manager</APIProxy>
    <ProxyEndpoint>default</ProxyEndpoint>
</LocalTargetConnection>

這個範例會建立對本機 API Proxy (即位於相同機構中的 Proxy) 的呼叫 和環境) 呼叫 data-manager,並指定其 Proxy 端點 為 default

<HTTPTargetConnection>
    <URL>http://example.com/{request.myResourcePath}</URL>
</HTTPTargetConnection>

這個範例會在網址中使用變數,以動態方式填入目標網址。 網址的 http:// 通訊協定部分,不得以 變數。另外,您必須對網址的網域部分使用不同的變數, 然後是網址其餘部分

<ServiceCallout name="ServiceCallout-GeocodingRequest1">
    <DisplayName>Inline request message</DisplayName>
    <Request variable="authenticationRequest">
      <Set>
        <QueryParams>
          <QueryParam name="address">{request.queryparam.postalcode}</QueryParam>
          <QueryParam name="region">{request.queryparam.country}</QueryParam>
          <QueryParam name="sensor">false</QueryParam>
        </QueryParams>
      </Set>
    </Request>
    <Response>GeocodingResponse</Response>
    <Timeout>30000</Timeout>
    <HTTPTargetConnection>
      <URL>http://maps.googleapis.com/maps/api/geocode/json</URL>
    </HTTPTargetConnection>
</ServiceCallout>
http://maps.googleapis.com/maps/api/geocode/json

不使用「指派訊息」之類的政策建立要求物件,您可以 直接在服務呼叫政策中定義。在這個示例中,服務呼叫政策 設定傳遞至外部服務的三個查詢參數值。您可以建立 Service Call 政策中可指定酬載、編碼類型的整個要求訊息 application/xml 等。 標題、表單參數等

以下為回應呼叫「服務呼叫圖」前產生的另一個範例 政策。

<ServiceCallout name="ServiceCallout-GeocodingRequest2">
    <Request clearPayload="false" variable="GeocodingRequest"/>
    <Response>GeocodingResponse</Response>
    <Timeout>30000</Timeout>
    <HTTPTargetConnection>
      <URL>http://maps.googleapis.com/maps/api/geocode/json</URL>
    </HTTPTargetConnection>
</ServiceCallout>

系統會從名為 GeocodingRequest 的變數中擷取要求訊息的內容 (可以是 )。系統會將回應訊息指派給 稱為 GeocodingResponse 的變數,其中 可透過「擷取變數」政策或以 JavaScript 編寫的自訂程式碼剖析 或 Java 的程式語言這項政策會等待 30 秒,直到 Google Geocoding API 的回應 逾時。

如需使用此範例服務呼叫範例的 API Proxy 完整範例,以及 指派訊息和擷取變數政策;詳情請參閱使用政策 組合

<ServiceCallout async="false" continueOnError="false" enabled="true" name="service-callout">
    <DisplayName>service-callout</DisplayName>
    <Properties/>
    <Request clearPayload="true" variable="myRequest">
        <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
    </Request>
    <Response>myResponse</Response>
    <HTTPTargetConnection>
        <LoadBalancer>
            <Algorithm>RoundRobin</Algorithm>
            <Server name="httpbin"/>
            <Server name="yahoo"/>
        </LoadBalancer>
        <Path>/get</Path>
    </HTTPTargetConnection>
</ServiceCallout>

這項政策會使用 LoadBalancer 屬性呼叫目標伺服器及執行負載平衡 。在此範例中,負載分散在兩個名為「httpbin」的目標伺服器 和「yahoo」;進一步瞭解如何為 Proxy 設定目標伺服器 負載平衡,請參閱這篇文章 後端伺服器


關於服務呼叫政策

在許多情況下,您可以在 API Proxy 中使用服務呼叫政策。適用對象 比方說,您可以設定 API Proxy 呼叫外部服務 地理位置資料、客戶評論、合作夥伴零售目錄中的商品等等。

摘要通常會搭配另外兩種政策使用:指派訊息和擷取變數。

  • 要求:指派訊息會填入傳送至遠端的要求訊息 課程中也會快速介紹 Memorystore 這是 Google Cloud 的全代管 Redis 服務
  • 回應:擷取變數會剖析回應並擷取 內容。

一般服務呼叫政策的組成包括:

  1. 指派訊息 policy:建立要求訊息、填入 HTTP 標頭、查詢參數、設定 HTTP 動詞等
  2. 服務摘要政策:參照指派訊息所建立的訊息 policy、定義外部呼叫的目標網址,以及定義回應物件的名稱 回應目標服務傳回的值

    如要改善效能,您也可以快取服務呼叫回應,如下文所述 Apigee 社群會話串:https://community.apigee.com/questions/34110/how-can-i-store-the-results-of-the-servicecallout.html
  3. 擷取變數 政策:通常定義 JSONPath 或 XPath 運算式,用來剖析產生的訊息 由服務呼叫所支援接著,政策會設定變數,其中包含從 服務呼叫回應。

請參閱使用政策 組合包含使用服務呼叫政策及服務呼叫政策的完整 API Proxy 範例 指派訊息和擷取變數政策

自訂錯誤處理

元素參照

以下為這項政策可設定的元素和屬性:

<ServiceCallout async="false" continueOnError="false" enabled="true" name="Service-Callout-1">
    <DisplayName>Custom label used in UI</DisplayName>
    <Request clearPayload="true" variable="myRequest">
        <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
        <Remove>
            <ReasonPhrase/>
            <StatusCode/>
            <Path/>
            <Version/>
            <Verb/>
         </Remove>
         <Copy>
            <ReasonPhrase/>
            <StatusCode/>
            <Path/>
            <Version/>
            <Verb/>
        </Copy>
        <Add>
            <Headers/>
            <QueryParams/>
            <FormParams/>
        </Add>
        <Set>
            <Headers/>
            <QueryParams/>
            <FormParams/>
            <Payload/>
            <ReasonPhrase/>
            <StatusCode/>
            <Path/>
            <Version/>
            <Verb/>
        </Set>
    </Request>
    <Response>calloutResponse</Response>
    <Timeout>30000</Timeout>
    <HTTPTargetConnection>
        <URL>http://example.com</URL>
        <LoadBalancer/>
        <SSLInfo/>
        <Properties/>
    </HTTPTargetConnection>
    <LocalTargetConnection>
        <APIProxy/>
        <ProxyEndpoint/>
        <Path/>
    </LocalTargetConnection>
</ServiceCallout>

&lt;ServiceCallout&gt;屬性

<ServiceCallout async="false" continueOnError="false" enabled="true" name="Service-Callout-1">

下表說明所有政策父項元素的共同屬性:

屬性 說明 預設 存在必要性
name

政策的內部名稱。name 屬性的值可以 包含英文字母、數字、空格、連字號、底線和半形句號。此值不能 超過 255 個半形字元

視需要使用 <DisplayName> 元素,為政策加上標籤: 管理使用者介面 Proxy 編輯器,使用不同的自然語言名稱。

不適用 必填
continueOnError

如果設為「false」,系統會在政策失敗時傳回錯誤。這是可預期的情況 大多數政策的行為

如果設為 true,即使政策已發生,流程執行作業仍會繼續執行 失敗。

false 選用
enabled

如要強制執行政策,請設為 true

設為 false 即可停用政策。這項政策不會 仍會強制執行 政策。

true 選用
async

此屬性已淘汰。

false 已淘汰

&lt;DisplayName&gt;元素

name 屬性外,一併使用 管理 UI Proxy 編輯器,使用不同的自然語言名稱。

<DisplayName>Policy Display Name</DisplayName>
預設

不適用

如果省略這個元素,政策的 name 屬性值會是

存在必要性 選用
類型 字串

&lt;Request&gt;元素

指定內含要求訊息的變數,該訊息會從 API Proxy 傳送至 其他服務。變數可由流程中的現有政策建立,也可以建立該變數 服務呼叫政策的內嵌項目。

<Request clearPayload="true" variable="myRequest">
    <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
    <Remove>
        <ReasonPhrase/>
        <StatusCode/>
        <Path/>
        <Version/>
        <Verb/>
    </Remove>
    <Copy>
        <ReasonPhrase/>
        <StatusCode/>
        <Path/>
        <Version/>
        <Verb/>
    </Copy>
    <Add>
        <Headers/>
        <QueryParams/>
        <FormParams/>
    </Add>
    <Set>
        <Headers/>
        <QueryParams/>
        <FormParams/>
        <Payload/>
        <ReasonPhrase/>
        <StatusCode/>
        <Path/>
        <Version/>
        <Verb/>
    </Set>
</Request>

<Remove><Copy><Add><Set> 標記的語法與 指定訊息 政策

如果要求訊息無法解析或無效,政策會傳回錯誤 要求訊息類型。

在最簡單的範例中,您傳遞的變數包含已填入的要求訊息 執行以下作業:

<Request clearPayload="true" variable="myRequest"/>

或者,您也可以在服務呼叫政策本身中,填入傳送至外部服務的要求訊息:

<Request>
  <Set>
    <Headers>
      <Header name="Accept">application/json</Header>
    </Headers>
    <Verb>POST</Verb>
    <Payload contentType="application/json">{"message":"my test message"}</Payload>
  </Set>
  <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
</Request>
預設 如果您省略 Request 元素或其任何屬性,Edge 會指派 下列預設值

&lt;Request clearPayload=&quot;true&quot;variable=&quot;servicecallout.request&quot;/&gt;

我們來看看這些預設值的意義。首先,clearPayload=true 表示 每次執行 Service callout 政策時,都會建立要求物件。也就是說 要求和要求 URI 路徑一律不會重複使用其次是預設變數 name (servicecallout.request) 是指派給要求的預留名稱 如未提供名稱

如果您使用的是資料遮罩功能,請務必瞭解這個預設名稱;如果您省略變數名稱, 您需要在遮罩設定中新增 servicecallout.request。例如: 如果您要遮蓋 Authorization 標頭,不讓它出現在 Trace 工作階段中, 請將下列內容新增至遮蓋設定,擷取預設名稱:

servicecallout.request.header.Authorization

外觀狀態 選用。
類型 不適用

屬性

屬性 說明 預設 存在必要性
變數

包含要求訊息的變數名稱。

servicecallout.request 選用
clearPayload

如果是 true,系統會在 會傳送至 HTTP 目標,釋出要求訊息使用的記憶體。

設定 clearPayload 僅在服務呼叫 執行狀態

true 選用

&lt;Request&gt;/&lt;IgnoreUnresolvedVariables&gt;元素

如果設為 true,政策會 會忽略要求中的任何未解決的變數錯誤。

<Request clearPayload="true" variable="myRequest">
    <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
</Request> 
預設 false
外觀狀態 選用
類型 布林值

&lt;Response&gt;元素

當 API Proxy 邏輯需要遠端呼叫的回應時,請加入此元素 需要進一步處理

使用這個元素時,它會指定包含 從外部服務接收的回應訊息。目標的回應會指派給 政策能成功讀取整個回應時,才會儲存這個變數。如果遠端通話 失敗,這項政策會傳回錯誤。

如果省略這個元素,API Proxy 不會等待回應。API Proxy 流程 隨著任何後續流程步驟繼續執行。此外,為了說明這個情況, Response 元素,則無法透過 ,而 Proxy 流程無法偵測遠端呼叫中的失敗情形。 使用 Service callout 時省略 Response 元素的常見用途:記錄 傳送至外部系統

 <Response>calloutResponse</Response> 
預設 不適用
外觀狀態 選用
類型 字串

<逾時>元素

服務呼叫政策等待回應 目標。您無法在執行階段動態設定這個值。如果服務呼叫達到逾時, 如果傳回 HTTP 500,政策就會失敗,且 API Proxy 進入錯誤狀態, 請參閱「處理錯誤」一節。

<Timeout>30000</Timeout>
預設 Apigee 的預設 HTTP 逾時設定是 55,000 毫秒 (55 秒), 邊緣
外觀狀態 選用
類型 整數

&lt;HTTPTargetConnection&gt;元素

提供網址、TLS/SSL 和 HTTP 屬性等傳輸詳細資料。詳情請參閱 <TargetEndpoint> 設定參考資料。

<HTTPTargetConnection>
    <URL>http://example.com</URL>
    <LoadBalancer/>
    <SSLInfo/>
    <Properties/>
</HTTPTargetConnection>
預設 不適用
外觀狀態 必填
類型 不適用

&lt;HTTPTargetConnection&gt;/&lt;URL&gt;元素

要呼叫的服務的網址:

<HTTPTargetConnection>
    <URL>http://example.com</URL>
</HTTPTargetConnection>

您可以使用變數動態提供部分網址。不過,通訊協定部分 下方的 http:// 網址,不可以是 變數指定的變數在下一個範例中,您將使用變數指定查詢的值 參數:

<URL>http://example.com/forecastrss?w=${request.header.woeid}</URL>

或者,您也可以使用變數來設定部分網址路徑:

<URL>http://example.com/{request.resourcePath}?w=${request.header.woeid}</URL>

如要使用變數指定網址的網域和通訊埠,請使用單一變數 以及第二個變數 (用於網址其他部分):

<URL>http://{request.dom_port}/{request.resourcePath}</URL>
預設 不適用
外觀狀態 必填
類型 字串

&lt;HTTPTargetConnection&gt;/&lt;SSLInfo&gt;元素

後端服務的 TLS/SSL 設定。如需 TLS/SSL 設定的說明,請參閱 設定 TLS 從邊緣到後端 (Cloud 和私有雲) 以及「TLS/SSL 目標端點設定」 API Proxy 設定參考資料

<HTTPTargetConnection>
    <URL>https://example.com</URL>
    <SSLInfo>
        <Enabled>true</Enabled>
        <ClientAuthEnabled>true</ClientAuthEnabled>
        <KeyStore>ref://mykeystoreref</KeyStore>  ## Use of a reference is recommended
        <KeyAlias>myKey</KeyAlias>
        <TrustStore>myTruststore</TrustStore>
        <Ciphers/>
        <Protocols/>
    </SSLInfo>
</HTTPTargetConnection>
預設 不適用
外觀狀態 選用
類型 不適用

&lt;HTTPTargetConnection&gt;/&lt;Properties&gt;元素

將 HTTP 傳輸屬性至後端服務。若需更多資訊,請參閲 端點屬性參考資料

<HTTPTargetConnection>
    <URL>http://example.com</URL>
    <Properties>
        <Property name="allow.http10">true</Property>
        <Property name="request.retain.headers">
          User-Agent,Referer,Accept-Language
        </Property>
    </Properties>
</HTTPTargetConnection>
預設 不適用
外觀狀態 選用
類型 不適用

&lt;HTTPTargetConnection&gt;/&lt;LoadBalancer&gt;元素

呼叫一或多個目標伺服器,然後在這些伺服器上執行負載平衡。請參閱來電目標 伺服器,請參閱範例區段中的範例。另請參閱「跨後端負載平衡 伺服器。另請瀏覽這個社群 貼文,討論如何透過服務呼叫政策和 建立防火牆規則

<HTTPTargetConnection> <LoadBalancer> <Algorithm>RoundRobin</Algorithm> <Server name="httpbin"/> <Server name="yahoo"/> </LoadBalancer> <Path>/get</Path> </HTTPTargetConnection>
預設 不適用
外觀狀態 選用
類型 不適用

&lt;LocalTargetConnection&gt;元素

指定本機 Proxy (即位於相同的機構和環境中的 Proxy),做為 服務摘要的目標。

如要進一步指定目標,請使用 <APIProxy><ProxyEndpoint> 元素,或是 <Path> 元素。

<LocalTargetConnection>
   <APIProxy/>
   <ProxyEndpoint/>
   <Path/>
</LocalTargetConnection>
預設 不適用
外觀狀態 必填
類型 不適用

&lt;LocalTargetConnection&gt;/&lt;APIProxy&gt;元素

做為本機呼叫目標的 API Proxy 名稱,Proxy 必須位在 和環境。

<LocalTargetConnection>
   <APIProxy>data-manager</APIProxy>
   <ProxyEndpoint>default</ProxyEndpoint>
</LocalTargetConnection>

除了 <APIProxy> 元素之外,請同時加入 <ProxyEndpoint> 元素,用於指定應使用哪個 Proxy 端點的名稱 只有 要能參與通話

<LocalTargetConnection>
   <APIProxy/>
   <ProxyEndpoint/>
</LocalTargetConnection> 
預設 不適用
外觀狀態 必填
類型 字串

&lt;LocalTargetConnection&gt;/&lt;ProxyEndpoint&gt;元素

應做為呼叫目標的 Proxy 端點名稱。這是位於 使用 <APIProxy> 元素指定的 API Proxy。

<LocalTargetConnection>
   <APIProxy>data-manager</APIProxy>
   <ProxyEndpoint>default</ProxyEndpoint>
</LocalTargetConnection>
預設 不適用
外觀狀態 選用
類型 不適用

&lt;LocalTargetConnection&gt;/&lt;Path&gt;元素

指向目標端點的路徑。端點必須參照位於 和環境。

如果不需要,請使用這個組合,而不要使用 <APIProxy>/<ProxyEndpoint> 組合 或無法依賴 -- Proxy 名稱路徑可能是可靠的目標。

<LocalTargetConnection>
   <Path>/data-manager</Path>
</LocalTargetConnection>
預設 不適用
外觀狀態 選用
類型 不適用

結構定義

流程變數

流程變數會根據 HTTP 在執行階段啟用政策和流程的動態行為 標頭、郵件內容或流程背景資訊可用的預先定義 Flow 變數如下 執行服務呼叫政策後。如要進一步瞭解流程變數,請參閱變數參考資料

服務呼叫有自己的要求和回應,您可以透過 變數。因為主要訊息使用 request.*response.* 變數前置字元,請使用 myrequest.*calloutResponse.* 前置字串 (服務呼叫設定中的預設值) 至 取得服務摘要專屬的訊息資料。下表的第一個範例顯示 如何在服務呼叫中取得 HTTP 標頭。

變數 說明

以下為取得服務呼叫要求和回應標頭的示例 就像從主要要求和回應取得標頭的方法一樣

calloutResponse.header.HeaderName

myRequest.header.HeaderName

其中 calloutResponse 是服務中回應的變數名稱 呼叫,而 myRequest 是要求的變數名稱。例如:

calloutResponse.header.Content-Length

會傳回服務呼叫回應的 Content-Length 標頭。

範圍:從服務摘要開始
類型:字串
權限:讀取/寫入

服務呼叫要求或回應中的訊息標頭。舉例來說 Proxy 目標為 http://example.com,而服務呼叫目標為 http://mocktarget.apigee.net,這些變數是呼叫 http://mocktarget.apigee.net.

servicecallout.requesturi

範圍:從服務呼叫要求轉送
類型:字串
權限:讀取/寫入

服務呼叫政策的 TargetEndpoint URI。URI 是 TargetEndpoint URL 並未包含通訊協定和網域規格

servicecallout.{policy-name}.target.url

範圍:從服務呼叫要求轉送
類型:字串
權限:讀取/寫入

服務呼叫的目標網址。

calloutResponse.content

其中 calloutResponse<Response> 變數名稱 已設定為服務摘要

範圍:取自服務呼叫回應
類型:字串
權限:讀取/寫入

服務呼叫的回應主體。

servicecallout.{policy-name}.expectedcn

範圍:從服務呼叫要求轉送
類型:字串
權限:讀取/寫入

服務呼叫中提及的目標端點預期通用名稱 政策。只有在 TargetEndpoint 參照 TLS/SSL 時,才有意義 端點

servicecallout.{policy-name}.failed

範圍:取自服務呼叫回應
類型:布林值
權限:讀取/寫入

布林值,指出政策是否成功、false 或失敗,true。

錯誤

This section describes the fault codes and error messages that are returned and fault variables that are set by Edge when this policy triggers an error. This information is important to know if you are developing fault rules to handle faults. To learn more, see What you need to know about policy errors and Handling faults.

Runtime errors

These errors can occur when the policy executes.

Fault code HTTP status Cause Fix
steps.servicecallout.ExecutionFailed 500

This error can occur when:

  • the policy is asked to handle input that is malformed or otherwise invalid.
  • the backend target service returns an error status (by default, 4xx or 5xx).
steps.servicecallout.RequestVariableNotMessageType 500 The Request variable specified in the policy is not of type Message. For example, if it's a string or other non-message type, you'll see this error.
steps.servicecallout.RequestVariableNotRequestMessageType 500 The Request variable specified in the policy is not of type Request Message. For example, if it's a Response type, you'll see this error.

Deployment errors

These errors can occur when you deploy a proxy containing this policy.

Error name Cause Fix
URLMissing The <URL> element inside <HTTPTargetConnection> is missing or empty.
ConnectionInfoMissing This error happens if the policy does not have an <HTTPTargetConnection> or <LocalTargetConnection> element.
InvalidTimeoutValue This error happens if the <Timeout> value is negative or zero.

Fault variables

These variables are set when a runtime error occurs. For more information, see What you need to know about policy errors.

Variables Where Example
fault.name="fault_name" fault_name is the name of the fault, as listed in the Runtime errors table above. The fault name is the last part of the fault code. fault.name = "RequestVariableNotMessageType"
servicecallout.policy_name.failed policy_name is the user-specified name of the policy that threw the fault. servicecallout.SC-GetUserData.failed = true

Example error response

{  
   "fault":{  
      "detail":{  
         "errorcode":"steps.servicecallout.RequestVariableNotMessageType"
      },
      "faultstring":"ServiceCallout[ServiceCalloutGetMockResponse]: 
            request variable data_str value is not of type Message"
   }
}

Example fault rule

<faultrule name="VariableOfNonMsgType"></faultrule><FaultRule name="RequestVariableNotMessageType">
    <Step>
        <Name>AM-RequestVariableNotMessageType</Name>
    </Step>
    <Condition>(fault.name = "RequestVariableNotMessageType")</Condition>
</FaultRule>

相關主題