ServiceCallout 政策

本页面适用于 ApigeeApigee Hybrid

查看 Apigee Edge 文档。

政策图标

内容

通过 ServiceCallout 政策,您可以通过 API 代理流调用其他服务。您可以调用外部服务(例如外部 RESTful 服务端点)或内部服务(如同一组织和环境中的 API 代理)。

此政策是一项可扩展政策,使用此政策可能会影响费用或使用情况,具体取决于您的 Apigee 许可。如需了解政策类型和使用情况影响,请参阅政策类型

  • 在外部用例中,您调用代理外部的第三方 API。系统会解析来自该第三方 API 的响应并插入到您的 API 响应消息中,以丰富和“遮盖”向应用最终用户显示的数据。您还可以在请求流中使用 ServiceCallout 政策发出请求,然后将响应中的信息传递给 API 代理的 TargetEndpoint。
  • 在另一个用例中,您调用与发起调用的代理位于同一组织和环境中的代理。例如,当您有一个代理提供了其他代理将使用的一个或多个离散的低级功能时,您可能会发现此功能很有用。例如,使用后端数据存储公开创建/读取/更新/删除操作的代理可以是将数据公开给客户端的多个其他代理的目标代理。

该政策支持通过 HTTP 和 HTTPS 发送的请求。

示例

对内部代理进行本地调用

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

此示例创建对名为 data-manager 的本地 API 代理(即同一组织和环境中的代理)的调用,并指定其代理端点(名为 default)。

作为变量的网址

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

此示例在网址中使用变量来动态填充目标的网址。网址的协议部分 http:// 不能通过变量指定。此外,您还必须对网址的网域部分和网址的其余部分使用单独的变量。

Google 地理编码/定义请求

<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>https://maps.googleapis.com/maps/api/geocode/json</URL>
    </HTTPTargetConnection>
</ServiceCallout>

您可以直接在 ServiceCallout 政策中定义请求对象,而不是使用 AssignMessage 政策等政策来创建请求对象。在此示例中,ServiceCallout 政策会设置传递到外部服务的三个查询参数的值。您可以在 ServiceCallout 政策中创建完整的请求消息,以指定载荷、编码类型(如 application/xml)、标头、表单参数等。

再举一例:先创建请求,再实现 ServiceCallout 政策。

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

请求消息的内容是从名为 GeocodingRequest 的变量中提取的(该变量可通过例如 AssignMessage 政策填充)。响应消息被分配给名为 GeocodingResponse 的变量,在其中,它是要由 ExtractVariables 政策或以 JavaScript 或 Java 编写的自定义代码解析的变量。策略等待 30 秒以接收来自 Google Geocoding API 响应,此后将会超时。

调用目标服务器

<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 属性来调用目标服务器,并在这些服务器之间进行负载均衡。在此示例中,负载分布在名为 httpbinyahoo 的两个目标服务器中。如需了解如何为代理设置目标服务器以及如何配置负载均衡,请参阅在后端服务器之间进行负载均衡


ServiceCallout 政策简介

在很多情况下,您可以在 API 代理中使用 ServiceCallout 政策。例如,您可以配置 API 代理,以调用外部服务来提供地理位置数据、客户评价、合作伙伴零售目录中的商品等。

调用通常与另外两个政策结合使用:AssignMessage 和 ExtractVariables。

  • 请求:AssignMessage 会填充发送到远程服务的请求消息。
  • 响应:ExtractVariables 会解析响应并提取特定内容。

典型的 ServiceCallout 政策组合涉及:

  1. AssignMessage 政策:创建请求消息、填充 HTTP 标头、查询参数、设置 HTTP 谓词等。
  2. ServiceCallout 政策:引用由 AssignMessage 政策创建的消息、定义外部调用的目标网址以及定义目标服务返回的响应对象的名称。

    为了提升性能,您还可以缓存 ServiceCallout 响应,如如何将 ServiceCallout 政策的结果存储在缓存中?然后如何从缓存中检索它?所述

  3. ExtractVariables 政策:通常定义 JSONPath 或 XPath 表达式,以解析 ServiceCallout 生成的消息。然后,该政策会设置变量,其中包含从 ServiceCallout 响应解析的值。

自定义错误处理

元素参考

您可以在此政策中配置以下元素和属性:

<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>
            <StatusCode/>
            <Path/>
            <Version/>
            <Verb/>
         </Remove>
         <Copy>
            <StatusCode/>
            <Path/>
            <Version/>
            <Verb/>
        </Copy>
        <Add>
            <Headers/>
            <QueryParams/>
            <FormParams/>
        </Add>
        <Set>
            <Headers/>
            <QueryParams/>
            <FormParams/>
            <Payload/>
            <StatusCode/>
            <Path/>
            <Version/>
            <Verb/>
        </Set>
    </Request>
    <Response>calloutResponse</Response>
    <Timeout>30000</Timeout>
    <HTTPTargetConnection>
        <URL>http://example.com</URL>
        <LoadBalancer/>
        <SSLInfo/>
        <Properties/>
        <Authentication>
          <HeaderName ref="{variable}">STRING</HeaderName>
          <GoogleAccessToken>
            <Scopes>
              <Scope>https://www.googleapis.com/auth/cloud-platform</Scope>
            </Scopes>
            <LifetimeInSeconds ref="{variable}">3600</LifetimeInSeconds>
          </GoogleAccessToken>
        </Authentication>
        <Authentication>
          <HeaderName ref="{variable}">STRING</HeaderName>
          <GoogleIDToken>
            <Audience ref="{variable}" useTargetUrl="BOOLEAN">{hostname}</Audience>
            <IncludeEmail ref="{variable}">true</IncludeEmail>
          </GoogleIDToken>
        </Authentication>
    </HTTPTargetConnection>
    <LocalTargetConnection>
        <APIProxy/>
        <ProxyEndpoint/>
        <Path/>
    </LocalTargetConnection>
</ServiceCallout>

<ServiceCallout> 属性

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

The following table describes attributes that are common to all policy parent elements:

Attribute Description Default Presence
name

The internal name of the policy. The value of the name attribute can contain letters, numbers, spaces, hyphens, underscores, and periods. This value cannot exceed 255 characters.

Optionally, use the <DisplayName> element to label the policy in the management UI proxy editor with a different, natural-language name.

N/A Required
continueOnError

Set to false to return an error when a policy fails. This is expected behavior for most policies.

Set to true to have flow execution continue even after a policy fails. See also:

false Optional
enabled

Set to true to enforce the policy.

Set to false to turn off the policy. The policy will not be enforced even if it remains attached to a flow.

true Optional
async

This attribute is deprecated.

false Deprecated

<DisplayName> element

Use in addition to the name attribute to label the policy in the management UI proxy editor with a different, natural-language name.

<DisplayName>Policy Display Name</DisplayName>
Default

N/A

If you omit this element, the value of the policy's name attribute is used.

Presence Optional
Type String

<Request> 元素

指定包含从 API 代理发送到其他服务的请求消息的变量。该变量可由流中的先前政策创建,或者您可以在 ServiceCallout 政策中创建它。

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

<Remove><Copy><Add><Set> 标记的语法与 AssignMessage 政策相同。

如果请求消息无法解析或属于无效的请求消息类型,则该政策将返回错误。

在最简单的示例中,您传递一个变量,其中包含先前在 API 代理流中填充的请求消息:

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

或者,您可以填充在 ServiceCallout 政策本身中发送到外部服务的请求消息:

<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 元素或其任何属性,Apigee 将分配以下默认值

<Request clearPayload="true" variable="servicecallout.request"/>

我们来看看这些默认值的含义。首先,clearPayload=true 表示每次 ServiceCallout 政策执行时都会创建一个新的请求对象。这意味着请求和请求 URI 路径绝不会重复使用。其次,默认变量名称 servicecallout.request 是保留的名称,如果您未提供名称则会将它分配给请求。

如果您使用数据遮盖,则必须知道此默认名称 - 如果您省略变量名称,则需要将 servicecallout.request 添加到遮盖配置。例如,如果要遮盖授权标头以使其不显示在调试会话中,应将以下内容添加到遮盖配置以捕获默认名称:

servicecallout.request.header.Authorization

状态 可选。
类型 不适用

特性

特性 说明 默认 状态
变量

将包含请求消息的变量的名称。

servicecallout.request 可选
clearPayload

如果设置为 true,则在将请求发送到 HTTP 目标后,将会清除包含请求消息的变量,以释放请求消息使用的内存。

仅当执行 ServiceCallout 后需要请求消息时,才将 clearPayload 选项设置为 false。

true 可选

<Request>/<IgnoreUnresolvedVariables> 元素

如果设置为 true,该政策会忽略请求中任何无法解析的变量错误。

<Request clearPayload="true" variable="myRequest">
    <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
</Request>
默认 false
状态 可选
类型 布尔值

<Response> 元素

如果 API 代理逻辑需要来自远程调用的响应以进行进一步的处理,请包括此元素。

如果此元素存在,则它指定将包含从外部服务接收到的响应消息的变量名称。仅当该政策成功读取整个响应时,才会将来自目标的响应分配给变量。如果远程调用因任何原因失败,则该政策会返回错误。

如果省略此元素,API 代理不会等待响应;API 代理流会继续执行任何后续流步骤。此外,为了清楚说明,不带 Response 元素时,来自目标的响应不能在后续步骤中处理,并且代理流无法检测远程调用。使用 ServiceCallout 时省略 Response 元素的常见用例:将消息记录到外部系统。

 <Response>calloutResponse</Response>
默认 北美
状态 可选
类型 字符串

<Timeout> 元素

ServiceCallout 政策等待来自目标的响应的时间(以毫秒为单位)。无法在运行时动态设置此值。如果 ServiceCallout 遇到超时,则会返回 HTTP 500,政策将会失败,并且 API 代理会进入错误状态,如处理错误中所述。

<Timeout>30000</Timeout>
默认 55000 毫秒(55 秒),Apigee 的默认 HTTP 超时设置
状态 可选
类型 整数

<HTTPTargetConnection> 元素

提供传输详细信息,例如网址、TLS/SSL 和 HTTP 属性。请参阅 <TargetEndpoint> 配置参考。

<HTTPTargetConnection>
    <URL>http://example.com</URL>
    <LoadBalancer/>
    <SSLInfo/>
    <Properties/>
</HTTPTargetConnection>
默认 不适用
状态 必需
类型 不适用

<HTTPTargetConnection>/<Authentication> 元素

生成 Google OAuth 2.0 或 Google 颁发的 OpenID Connect 令牌,以对 Google 服务以及在某些 Google Cloud 产品(例如 Cloud FunctionsCloud Run)上运行的自定义服务进行经过身份验证的调用。使用此元素需要执行使用 Google 身份验证中所述的设置和部署步骤。正确设置后,政策会为您创建身份验证令牌,并将其添加到服务请求中。

子元素 GoogleAccessTokenGoogleIDToken 可让您配置政策以生成 Google OAuth 或 OpenID Connect 令牌。您需要根据要调用的服务类型选择其中一个子元素。

ServiceCallout 政策仅支持调用基于 HTTP 的服务。

默认 不适用
是否必需? 可选。
类型 复杂类型
父元素 <HTTPTargetConnection>
子元素 <HeaderName>
<GoogleAccessToken>
<GoogleIDToken>

Authentication 元素使用以下语法:

语法

<ServiceCallout>
...
  <HTTPTargetConnection>
    <Authentication>
      <HeaderName ref="FLOW_VARIABLE">STRING</HeaderName>
      <GoogleAccessToken>
        <Scopes>
          <Scope>SCOPE</Scope>
          ...
        </Scopes>
        <!-- NOTE: The default value for LifetimeInSeconds is 3600. Change the default only
        if you want to limit the risk of leaked access tokens or improve performance. -->
        <LifetimeInSeconds ref="{variable}">INTEGER</LifetimeInSeconds>
      </GoogleAccessToken>

    --OR--
      <HeaderName ref="FLOW_VARIABLE">STRING</HeaderName>
      <GoogleIDToken>
        <Audience ref="{variable}" useTargetUrl="BOOLEAN">STRING</Audience>
        <IncludeEmail ref="{variable}">BOOLEAN</IncludeEmail>
      </GoogleIDToken>
    </Authentication>
  </HTTPTargetConnection>
</ServiceCallout>

使用 GoogleAccessToken

以下示例展示了 GoogleAccessToken 元素:

<Authentication>
  <GoogleAccessToken>
    <Scopes>
      <Scope>https://www.googleapis.com/auth/cloud-platform</Scope>
    </Scopes>
  </GoogleAccessToken>
</Authentication>

使用 GoogleIDToken

以下示例展示了 GoogleIDToken 元素:

<Authentication>
  <GoogleIDToken>
      <Audience>https://httpserver0-bar.run.app</Audience>
      <IncludeEmail>false</IncludeEmail>
  </GoogleIDToken>
</Authentication>

使用 HeaderName

以下示例展示了 HeaderName 元素:

  <Authentication>
    <HeaderName>X-Serverless-Authorization</HeaderName>
    <GoogleAccessToken>
      <Scopes>
        <Scope>"https://www.googleapis.com/auth/cloud-platform"</Scope>
      </Scopes>
    </GoogleAccessToken>
  </Authentication>

使用 LifetimeInSeconds

以下示例展示了 HeaderName 元素:

  <Authentication>
    <GoogleAccessToken>
      <Scopes>
        <Scope>"https://www.googleapis.com/auth/cloud-platform"</Scope>
      </Scopes>
      <LifetimeInSeconds ref="variable">3600</LifetimeInSeconds>
    </GoogleAccessToken>
  </Authentication>

特性

无。

HeaderName 子元素

默认情况下,如果存在 Authentication 配置,Apigee 会生成不记名令牌,并将其注入到发送到目标系统的消息中的 Authorization 标头。HeaderName 元素可让您指定其他标头的名称来保存该不记名令牌。如果目标是使用 X-Serverless-Authorization 标头的 Cloud Run 服务,此功能尤其有用。Authorization 标头(如果存在)保持不变,并且也会在请求中发送。

默认 不适用
是否必需?
类型 字符串
父元素 <Authentication>
子元素

HeaderName 元素使用以下语法:

语法

<ServiceCallout>
...
  <Authentication>
    <HeaderName ref="FLOW_VARIABLE">STRING</HeaderName>
    <GoogleAccessToken>
      ...
    </GoogleAccessToken>
  </Authentication>
  ...
</ServiceCallout>

包含静态字符串

在此示例中,生成的不记名令牌默认添加到发送到目标系统的名为 X-Serverless-Authorization 的标头中。Authorization 标头(如果存在)保持不变,并且也会在请求中发送。

<Authentication>
  <HeaderName>X-Serverless-Authorization</HeaderName>
  <GoogleAccessToken>
    <Scopes>
      <Scope>https://www.googleapis.com/auth/cloud-platform</Scope>
    </Scopes>
  </GoogleAccessToken>
</Authentication>

包含变量引用

在此示例中,生成的不记名令牌默认添加到发送到目标系统的名为 X-Serverless-Authorization 的标头中。如果 my-variable 具有值,系统将使用该值而不是默认字符串。Authorization 标头(如果存在)保持不变,并且也会在请求中发送。

<Authentication>
  <HeaderName ref='my-variable'>X-Serverless-Authorization</HeaderName>
  <GoogleAccessToken>
    <Scopes>
      <Scope>https://www.googleapis.com/auth/cloud-platform</Scope>
    </Scopes>
  </GoogleAccessToken>
</Authentication>

GoogleAccessToken 子元素

生成 Google OAuth 2.0 令牌以对 Google 服务进行经过身份验证的调用。Google OAuth 令牌可用于调用多种 Google 服务,例如 Cloud LoggingSecret Manager

默认 不适用
是否必需? 必须存在 GoogleAccessTokenGoogleIDToken 子元素。
类型 字符串
父元素 <Authentication>
子元素 <Scopes>
<LifetimeInSeconds>

GoogleAccessToken 元素使用以下语法:

语法

<ServiceCallout>
...
  <Authentication>
    <GoogleAccessToken>
      <Scopes>
        <Scope>SCOPE_1</Scope>
        ...
      </Scopes>
      <!-- NOTE: The default value for LifetimeInSeconds is 3600. We do not recommend changing
      the default unless you want to limit the risk of leaked access tokens or improve performance. -->
      <LifetimeInSeconds ref="FLOW_VARIABLE">INTEGER</LifetimeInSeconds>
    </GoogleAccessToken>
  </Authentication>
  ...
</ServiceCallout>

示例 1

以下示例展示了 GoogleAccessToken 元素:

<Authentication>
  <GoogleAccessToken>
    <Scopes>
      <Scope>https://www.googleapis.com/auth/cloud-platform</Scope>
    </Scopes>
  </GoogleAccessToken>
</Authentication>

示例 2

以下示例展示了如何连接到 Secret Manager 以使用 ServiceCallout 政策检索密文。

<ServiceCallout name="ServiceCallout-sm">
  <Response>SecretManagerResponse</Response>
  <Timeout>30000</Timeout>
  <HTTPTargetConnection>
    <Authentication>
      <GoogleAccessToken>
        <Scopes>
          <Scope>https://www.googleapis.com/auth/cloud-platform</Scope>
        </Scopes>
      </GoogleAccessToken>
    </Authentication>
    <URL>
      https://secretmanager.googleapis.com/v1/projects/project-id/secrets/secret-id
    </URL>
  </HTTPTargetConnection>
</ServiceCallout>

示例 3

以下示例展示了如何通过 ServiceCallout 政策调用 Cloud Run。

<ServiceCallout name="ServiceCallout-CloudRun">
  <Response>CloudRunResponse</Response>
  <Timeout>30000</Timeout>
  <HTTPTargetConnection>
    <Authentication>
      <GoogleIDToken>
        <Audience>https://cloudrun-hostname.a.run.app/test</Audience>
      </GoogleIDToken>
    </Authentication>
    <URL>https://cloudrun-hostname.a.run.app/test</URL>
  </HTTPTargetConnection>
</ServiceCallout>

Scopes 子元素

标识要包含在 OAuth 2.0 访问令牌中的范围。如需了解详情,请参阅 适用于 Google API 的 OAuth 2.0 范围。您可以在此元素下添加一个或多个 <Scope> 子元素。

默认 不适用
是否必需? 必需
类型 字符串
父元素 <GoogleAccessToken>
子元素 <Scope>

Scope 子元素

指定有效的 Google API 范围。如需了解详情,请参阅 适用于 Google API 的 OAuth 2.0 范围

默认 不适用
是否必需? 必须提供至少一个值。
类型 字符串
父元素 <Scopes>
子元素 无。

LifetimeInSeconds 子元素

指定访问令牌的生命周期长度(以秒为单位)。

默认 3600
是否必需? 可选
类型 整数
父元素 <GoogleAccessToken>
子元素 无。

GoogleIDToken 子元素

生成 Google 颁发的 OpenID Connect 令牌,以对 Google 服务进行经过身份验证的调用。

默认 不适用
是否必需? 必须存在 GoogleAccessTokenGoogleIDToken 子元素。
类型 字符串
父元素 <Authentication>
子元素 <Audience>
<IncludeEmail>

GoogleIDToken 元素使用以下语法:

语法

<ServiceCallout>
...
  <Authentication>
    <GoogleIDToken>
        <Audience ref="{variable}" useTargetUrl="BOOLEAN">STRING</Audience>
        <IncludeEmail ref="{variable}">BOOLEAN</IncludeEmail>
    </GoogleIDToken>
  </Authentication>
</ServiceCallout>

示例 1

以下示例展示了 GoogleIDToken 元素:

<Authentication>
  <GoogleIDToken>
      <Audience>https://httpserver0-bar.run.app</Audience>
      <IncludeEmail>true</IncludeEmail>
  </GoogleIDToken>
</Authentication>

Audience 子元素

生成的身份验证令牌的目标对象,例如令牌授予访问权限的 API 或账号。

如果 Audience 的值为空或 ref 变量未解析为有效值,并且 useTargetUrltrue,则使用目标的网址(不包括任何查询参数)作为目标对象。默认情况下,useTargetUrlfalse

<Audience>explicit-audience-value-here</Audience>

or:

<Audience ref='variable-name-here'/>

or:

<Audience ref='variable-name-here' useTargetUrl='true'/>

or:

<Audience useTargetUrl='true'/>
默认 不适用
是否必需? 必需
类型 字符串
父元素 <GoogleIDToken>
子元素 无。

includeEmail 子元素

如果此属性设置为 true,则生成的身份验证令牌将包含服务账号 emailemail_verified 声明。

默认 false
是否必需? 可选
类型 布尔值
父元素 <GoogleIDToken>
子元素 无。

<HTTPTargetConnection>/<URL> 元素

要调用的服务的网址:

<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>
默认 不适用
状态 必需
类型 字符串

<HTTPTargetConnection>/<SSLInfo> 元素

后端服务的 TLS/SSL 配置。如需有关 TLS/SSL 配置的帮助,请参阅 API 代理配置参考文档中的配置 TLS 的选项和“TLS/SSL TargetEndpoint 配置”。

<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>
默认 不适用
状态 可选
类型 不适用

<HTTPTargetConnection>/<Properties> 元素

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>
默认 不适用
状态 可选
类型 不适用

<HTTPTargetConnection>/<LoadBalancer> 元素

调用一个或多个目标服务器,并在这些服务器之间进行负载均衡。请参阅“示例”部分中的调用目标服务器示例。另请参阅跨后端服务器的负载均衡。另请参阅目标端点/服务器调用,其中介绍了从 ServiceCallout 政策和使用路由规则调用目标服务器的方法。

<HTTPTargetConnection> <LoadBalancer> <Algorithm>RoundRobin</Algorithm> <Server name="httpbin"/> <Server name="yahoo"/> </LoadBalancer> <Path>/get</Path> </HTTPTargetConnection>
默认 不适用
状态 可选
类型 不适用

<LocalTargetConnection> 元素

指定本地代理(即在同一组织和环境中的代理)作为服务调用的目标。

如需进一步指定目标,请使用 <APIProxy><ProxyEndpoint> 元素或 <Path> 元素。

<LocalTargetConnection>
   <APIProxy/>
   <ProxyEndpoint/>
   <Path/>
</LocalTargetConnection>
默认 不适用
状态 必需
类型 不适用

<LocalTargetConnection>/<APIProxy> 元素

作为本地调用的目标的 API 代理的名称。代理必须与发起调用的代理位于同一组织和环境中。

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

<APIProxy> 元素外,还可包括 <ProxyEndpoint> 元素,以指定作为调用目标的代理端点的名称。

<LocalTargetConnection>
   <APIProxy/>
   <ProxyEndpoint/>
</LocalTargetConnection>
默认 不适用
状态 必需
类型 字符串

<LocalTargetConnection>/<ProxyEndpoint> 元素

应作为调用目标的代理端点的名称。这是使用 <APIProxy> 元素指定的 API 代理中的代理端点。

<LocalTargetConnection>
   <APIProxy>data-manager</APIProxy>
   <ProxyEndpoint>default</ProxyEndpoint>
</LocalTargetConnection>
默认 不适用
状态 可选
类型 不适用

<LocalTargetConnection>/<Path> 元素

指向要作为目标的端点的路径。端点必须引用与发起调用的代理位于同一组织和环境中的代理。

如果您不知道或无法依赖代理名称,请使用此标记而不是 <APIProxy>/<ProxyEndpoint> 对。该路径可能是可靠的目标。

<LocalTargetConnection>
   <Path>/data-manager</Path>
</LocalTargetConnection>
默认 不适用
状态 可选
类型 不适用

架构

流变量

流变量可以在运行时基于 HTTP 标头、消息内容或流上下文支持政策和流的动态行为。在 ServiceCallout 政策执行后,以下预定义的流变量可用。如需详细了解流变量,请参阅流变量参考

ServiceCallout 具有自己的请求和响应,您可以通过变量访问这些数据。由于主要消息使用 request.*response.* 变量前缀,因此请使用 myrequest.*calloutResponse.* 前缀(ServiceCallout 配置中的默认值)来获取特定于 ServiceCallout 的消息数据。下表中的第一个示例演示了如何获取 ServiceCallout 中的 HTTP 标头。

变量 说明

以下示例展示了如何获取 ServiceCallout 请求和响应标头,与获取主请求和响应中的标头的方法类似。

calloutResponse.header.HeaderName

myRequest.header.HeaderName

其中,calloutResponse 是 ServiceCallout 中响应的变量名称,myRequest 是请求的变量名称。例如:

calloutResponse.header.Content-Length

返回 ServiceCallout 响应的 Content-Length 标头。

范围:来自 ServiceCallout 转发
类型:字符串
权限:读写

ServiceCallout 请求或响应中的消息标头。例如,如果 API 代理目标是 http://example.com,而 ServiceCallout 目标是 http://mocktarget.apigee.net,则这些变量是调用 http://mocktarget.apigee.net 的标头。

servicecallout.requesturi

范围:来自 ServiceCallout 请求转发
类型:字符串
权限:读写

ServiceCallout 政策的 TargetEndpoint URI。该 URI 是不包含协议和网域规范的 TargetEndpoint 网址。

servicecallout.{policy-name}.target.url

范围:来自 ServiceCallout 请求转发
类型:字符串
权限:读写

ServiceCallout 的目标网址。

calloutResponse.content

其中,calloutResponse 是 ServiceCallout 配置中的 <Response> 变量名称。

范围:来自 ServiceCallout 响应转发
类型:字符串
权限:读写

ServiceCallout 的响应正文。

servicecallout.{policy-name}.expectedcn

范围:来自 ServiceCallout 请求转发
类型:字符串
权限:读写

在 ServiceCallout 政策中引用的 TargetEndpoint 的预期通用名称。仅当 TargetEndpoint 指的是 TLS/SSL 端点时,该名称才有意义。

servicecallout.{policy-name}.failed

范围:来自 ServiceCallout 响应转发
类型:布尔值
权限:读写

布尔值指示政策是成功 (false) 还是失败 (true)。

错误

本部分介绍当此政策触发错误时返回的故障代码和错误消息,以及由 Apigee 设置的故障变量。在开发故障规则以处理故障时,请务必了解此信息。如需了解详情,请参阅您需要了解的有关政策错误的信息处理故障

运行时错误

政策执行时可能会发生这些错误。

故障代码 HTTP 状态 原因 修复
steps.servicecallout.ExecutionFailed 500

在以下情况下可能会发生此错误:

  • 要求政策处理输入格式错误或无效的输入。
  • 后端目标服务返回错误状态(默认为 4xx5xx)。
steps.servicecallout.RequestVariableNotMessageType 500 在政策中指定的 Request 变量不是 Message 类型。例如,如果是字符串或其他非消息类型,您将看到此错误。
steps.servicecallout.RequestVariableNotRequestMessageType 500 在政策中指定的 Request 变量不是 RequestMessage 类型。例如,如果是 Response 类型,您将看到此错误。
googletoken.EmptyIDTokenAudience 500

<GoogleIDToken> 已启用,但 useTargetUrl 设置为 false,并且未在错误发生时直接或通过引用为 <Audience> 提供值。

messaging.adaptors.http.filter.GoogleTokenGenerationFailure 500 如果为 API 代理配置了 <Authentication> 元素,可能会发生此错误。可能的原因包括:
  • 使用代理部署的服务账号:
    • 您的项目中不存在
    • 已停用
    • (仅限 Apigee Hybrid)未授予 apigee-runtime 服务账号的 roles/iam.serviceAccountTokenCreator 角色。
  • apigee-runtime 服务账号的来源项目中停用了 IAMCredentials API。
  • 使用了 <GoogleAccessToken> 元素,并且提供了一个或多个无效范围。例如,查找拼写错误或空的范围。
  • 仅针对 Apigee Hybrid,检查运行时容器的日志并搜索 GoogleTokenGenerationFailure,以查找可能有助于调试该问题的详细错误消息。

    部署错误

    在您部署包含此政策的代理时,可能会发生这些错误。

    错误名称 原因 修复
    URLMissing <HTTPTargetConnection> 中的 <URL> 元素缺失或为空。
    ConnectionInfoMissing 如果政策没有 <HTTPTargetConnection><LocalTargetConnection>元素,则会发生此错误。
    InvalidTimeoutValue 如果 <Timeout> 值为负或为零,则会发生此错误。
    FAILED_PRECONDITION 如果在使用 <Authentication> 标记配置代理时缺少服务账号,则会发生此错误。

    例如:

    
    Deployment of \"organizations/foo/apis/apiproxy/revisions/1\" requires a service
              account identity, but one was not provided with the request.
    PERMISSION_DENIED 如果在使用 <Authentication> 标记配置代理时服务账号出现权限问题,则会发生此错误。可能的原因:
    • 该服务账号不存在。
    • 服务账号不是在与 Apigee 组织相同的 Google Cloud 项目中创建的。
    • 部署者拥有服务账号的 iam.serviceAccounts.actAs 权限。如需了解详情,请参阅服务账号权限简介

    故障变量

    发生运行时错误时,系统会设置这些变量。如需了解详情,请参阅您需要了解的有关政策错误的信息

    变量 其中 示例
    fault.name="fault_name" fault_name 是故障名称,如上面的运行时错误表中所列。故障名称是故障代码的最后一部分。 fault.name = "RequestVariableNotMessageType"
    servicecallout.policy_name.failed policy_name 是抛出故障的政策的用户指定名称。 servicecallout.SC-GetUserData.failed = true

    错误响应示例

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

    故障规则示例

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

    相关主题