API 管理 Dapr 集成策略API Management Dapr integration policies

本主题提供 Dapr 集成 API 管理策略的参考。This topic provides a reference for Dapr integration API Management policies. Dapr 是一种可移植运行时,用于通过任何语言或框架来构建无状态和有状态的基于微服务的应用程序。Dapr is a portable runtime for building stateless and stateful microservices-based applications with any language or framework. 它能对常见的微服务模式进行编码,例如使用内置重试逻辑进行服务发现和调用,使用至少一次的传递语义进行发布和订阅,或者使用可插拔的绑定资源来简化使用外部服务的组合。It codifies the common microservice patterns, like service discovery and invocation with build-in retry logic, publish-and-subscribe with at-least-once delivery semantics, or pluggable binding resources to ease composition using external services. 请转到 dapr.io 以获取有关如何开始使用 Dapr 的详细信息和说明。Go to dapr.io for detailed information and instruction on how to get started with Dapr. 有关添加和配置策略的信息,请参阅 API 管理中的策略For information on adding and configuring policies, see Policies in API Management.

注意

本主题中引用的策略处于公共预览阶段,并且遵循 Azure 预览版补充使用条款Policies referenced in this topic are in Public Preview and are subject to Supplemental Terms of Use for Azure Previews.

重要

本主题中引用的策略仅在启用了 Dapr 支持的 API 管理网关的自承载版本中有效。Policies referenced in this topic work only in the self-hosted version of the API Management gateway with Dapr support enabled.

在自承载网关中启用 Dapr 支持Enable Dapr support in the self-hosted gateway

若要在自承载网关中启用 Dapr 支持,请将下面的 Dapr 注释添加到 Kubernetes 部署模板中,将“app-name”替换为所需的名称。To turn on Dapr support in the self-hosted gateway add the Dapr annotations below to the Kubernetes deployment template replacing "app-name" with a desired name. 此处提供了有关通过 Dapr 设置和使用 API 管理的完整演练。Complete walkthrough of setting up and using API Management with Dapr is available here.

template:
    metadata:
      labels:
        app: app-name
      annotations:
        dapr.io/enabled: "true"
        dapr.io/app-id: "app-name"

分布式 Application Runtime (Dapr) 集成策略Distributed Application Runtime (Dapr) integration policies

  • 发送对服务的请求:使用 Dapr 运行时查找 Dapr 微服务并与之进行可靠的通信。Send request to a service: Uses Dapr runtime to locate and reliably communicate with a Dapr microservice. 若要了解有关 Dapr 中服务调用的详细信息,请参阅这个 README 文件中的说明。To learn more about service invocation in Dapr, see the description in this README file.
  • 将消息发送到发布/订阅主题:使用 Dapr 运行时将消息发布到发布/订阅主题。Send message to Pub/Sub topic: Uses Dapr runtime to publish a message to a Publish/Subscribe topic. 若要了解有关 Dapr 中发布/订阅消息的详细信息,请参阅这个 README 文件中的说明。To learn more about Publish/Subscribe messaging in Dapr, see the description in this README file.
  • 触发器输出绑定:使用 Dapr 运行时通过输出绑定调用外部系统。Trigger output binding: Uses Dapr runtime to invoke an external system via output binding. 若要了解有关 Dapr 中绑定的详细信息,请参阅此 README 文件中的说明。To learn more about bindings in Dapr, see the description in this README file.

发送对服务的请求Send request to a service

此策略将当前请求的目标 URL 设置为 http://localhost:3500/v1.0/invoke/{app-id}[.{ns-name}]/method/{method-name},并且用策略语句中指定的值替换模板参数。This policy sets the target URL for the current request to http://localhost:3500/v1.0/invoke/{app-id}[.{ns-name}]/method/{method-name} replacing template parameters with values specified in the policy statement.

策略假设 Dapr 在网关所在的 pod 中的 sidecar 容器中运行。The policy assumes that Dapr runs in a sidecar container in the same pod as the gateway. 接收到请求后,Dapr 运行时执行服务发现和实际调用,包括 HTTP 和 gRPC 之间可能的协议转换、重试、分布式跟踪和错误处理。Upon receiving the request, Dapr runtime performs service discovery and actual invocation, including possible protocol translation between HTTP and gRPC, retries, distributed tracing, and error handling.

策略语句Policy statement

<set-backend-service backend-id="dapr" dapr-app-id="app-id" dapr-method="method-name" dapr-namespace="ns-name" />

示例Examples

示例Example

下面的示例演示如何在名为“echo”的微服务上调用名为“back”的方法。The following example demonstrates invoking the method named "back" on the microservice called "echo". set-backend-service 策略将目标 URL 设置为 http://localhost:3500/v1.0/invoke/echo.echo-app/method/backThe set-backend-service policy sets the destination URL to http://localhost:3500/v1.0/invoke/echo.echo-app/method/back. forward-request 策略将请求分派到 Dapr 运行时,Dapr 运行时将请求传递给微服务。The forward-request policy dispatches the request to the Dapr runtime, which delivers it to the microservice.

为清楚起见,forward-request 策略在这里显示。The forward-request policy is shown here for clarity. 策略通常通过 base 关键字从全局范围“继承”。The policy is typically "inherited" from the global scope via the base keyword.

<policies>
    <inbound>
        <base />
        <set-backend-service backend-id="dapr" dapr-app-id="echo" dapr-method="back" dapr-namespace="echo-app" />
    </inbound>
    <backend>
        <forward-request />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

元素Elements

元素Element 说明Description 必须Required
set-backend-serviceset-backend-service Root 元素Root element Yes

属性Attributes

属性Attribute 说明Description 必须Required 默认Default
backend-idbackend-id 必须设置为“dapr”Must be set to "dapr" Yes 不适用N/A
dapr-app-iddapr-app-id 目标微服务的名称。Name of the target microservice. 用于在 Dapr 中构成 appId 参数。Used to form the appId parameter in Dapr. Yes 不适用N/A
dapr-methoddapr-method 要在目标微服务上调用的方法或 URL 的名称。Name of the method or a URL to invoke on the target microservice. 映射到 Dapr 中的 method-name 参数。Maps to the method-name parameter in Dapr. Yes 空值N/A
dapr-namespacedapr-namespace 目标微服务所在的命名空间的名称。Name of the namespace the target microservice is residing in. 用于在 Dapr 中构成 appId 参数。Used to form the appId parameter in Dapr. No 空值N/A

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站Policy sections: inbound
  • 策略范围: 所有范围Policy scopes: all scopes

将消息发送到发布/订阅主题Send message to Pub/Sub topic

此策略指示 API 管理网关向 Dapr 发布/订阅主题发送消息。This policy instructs API Management gateway to send a message to a Dapr Publish/Subscribe topic. 策略通过向 http://localhost:3500/v1.0/publish/{{pubsub-name}}/{{topic}} 发出 HTTP POST 请求、替换模板参数并添加策略语句中指定的内容来实现这一点。The policy accomplishes that by making an HTTP POST request to http://localhost:3500/v1.0/publish/{{pubsub-name}}/{{topic}} replacing template parameters and adding content specified in the policy statement.

策略假设 Dapr 运行时正在网关所在的 pod 中的 sidecar 容器中运行。The policy assumes that Dapr runtime is running in a sidecar container in the same pod as the gateway. Dapr 运行时实现发布/订阅语义。Dapr runtime implements the Pub/Sub semantics.

策略语句Policy statement

<publish-to-dapr pubsub-name="pubsub-name" topic="topic-name" ignore-error="false|true" response-variable-name="resp-var-name" timeout="in seconds" template="Liquid" content-type="application/json">
    <!-- message content -->
</publish-to-dapr>

示例Examples

示例Example

下面的示例演示如何将当前请求的主体发送到“orders”发布/订阅组件的“new”主题The following example demonstrates sending the body of the current request to the "new" topic of the "orders" Pub/Sub component. 从 Dapr 运行时接收到的响应存储在 context 对象的“变量”集合的“daprresponse”项中。Response received from the Dapr runtime is stored in the "dapr-response" entry of the Variables collection in the context object.

例如,如果 Dapr 运行时找不到目标主题,并且响应错误,则会触发“on-error”部分。If Dapr runtime can't locate the target topic, for example, and responds with an error, the "on-error" section is triggered. 从 Dapr 运行时收到的响应被逐字返回给调用方。The response received from the Dapr runtime is returned to the caller verbatim. 否则,返回默认的 200 OK 响应。Otherwise, default 200 OK response is returned.

“backend”部分为空,请求不会转发到后端。The "backend" section is empty and the request is not forwarded to the backend.

<policies>
     <inbound>
        <base />
        <publish-to-dapr
           pubsub-name="orders"
               topic="new"
               response-variable-name="dapr-response">
            @(context.Request.Body.As<string>())
        </publish-to-dapr>
    </inbound>
    <backend>
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
        <return-response response-variable-name="pubsub-response" />
    </on-error>
</policies>

元素Elements

元素Element 说明Description 必需Required
publish-to-daprpublish-to-dapr Root 元素Root element Yes

属性Attributes

属性Attribute 说明Description 必须Required 默认Default
pubsub-namepubsub-name 目标 PubSub 组件的名称。The name of the target PubSub component. 映射到 Dapr 中的 pubsubname 参数。Maps to the pubsubname parameter in Dapr. 如果不存在,则 topic 属性值必须采用 pubsub-name/topic-name 形式。If not present, the topic attribute value must be in the form of pubsub-name/topic-name. No None
主题topic 主题的名称。The name of the topic. 映射到 Dapr 中的 topic 参数。Maps to the topic parameter in Dapr. Yes 空值N/A
ignore-errorignore-error 如果设置为 true,则指示策略在收到来自 Dapr 运行时的错误时不触发“on error”部分If set to true instructs the policy not to trigger "on-error" section upon receiving error from Dapr runtime No false
response-variable-nameresponse-variable-name 用于存储来自 Dapr 运行时的响应的变量集合项的名称Name of the Variables collection entry to use for storing response from Dapr runtime No None
timeouttimeout 等待 Dapr 运行时做出响应的时间(以秒为单位)。Time (in seconds) to wait for Dapr runtime to respond. 范围为 1 到 240 秒。Can range from 1 to 240 seconds. No 55
templatetemplate 用于转换消息内容的模板引擎。Templating engine to use for transforming the message content. “Liquid”是唯一支持的值。"Liquid" is the only supported value. No None
content-typecontent-type 消息内容的类型。Type of the message content. “application/json”是唯一支持的值。"application/json" is the only supported value. No None

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站、出站、错误时Policy sections: inbound, outbound, on-error
  • 策略范围: 所有范围Policy scopes: all scopes

触发器输出绑定Trigger output binding

此策略指示 API 管理网关触发出站 Dapr 绑定This policy instructs API Management gateway to trigger an outbound Dapr binding. 策略通过向 http://localhost:3500/v1.0/bindings/{{bind-name}} 发出 HTTP POST 请求、替换模板参数并添加策略语句中指定的内容来实现这一点。The policy accomplishes that by making an HTTP POST request to http://localhost:3500/v1.0/bindings/{{bind-name}} replacing template parameter and adding content specified in the policy statement.

策略假设 Dapr 运行时正在网关所在的 pod 中的 sidecar 容器中运行。The policy assumes that Dapr runtime is running in a sidecar container in the same pod as the gateway. Dapr 运行时负责调用绑定表示的外部资源。Dapr runtime is responsible for invoking the external resource represented by the binding.

策略语句Policy statement

<invoke-dapr-binding name="bind-name" operation="op-name" ignore-error="false|true" response-variable-name="resp-var-name" timeout="in seconds" template="Liquid" content-type="application/json">
    <metadata>
        <item key="item-name"><!-- item-value --></item>
    </metadata>
    <data>
        <!-- message content -->
    </data>
</invoke-dapr-binding>

示例Examples

示例Example

下面的示例演示了如何触发名为“external-systems”的出站绑定,其操作名称为“create”,元数据由两个名为“source”和“client-ip”的键/值项组成,并且主体来自原始请求。The following example demonstrates triggering of outbound binding named "external-systems" with operation name "create", metadata consisting of two key/value items named "source" and "client-ip", and the body coming from the original request. 从 Dapr 运行时接收到的响应在 context 对象的“变量”集合的“bind-response”项中捕获。Response received from the Dapr runtime is captured in the "bind-response" entry of the Variables collection in the context object.

如果 Dapr 运行时由于某种原因而失败并返回错误,则会触发“on-error”部分,并且从 Dapr 运行时收到的响应会逐字返回给调用方。If Dapr runtime fails for some reason and responds with an error, the "on-error" section is triggered and response received from the Dapr runtime is returned to the caller verbatim. 否则,返回默认的 200 OK 响应。Otherwise, default 200 OK response is returned.

“backend”部分为空,请求不会转发到后端。The "backend" section is empty and the request is not forwarded to the backend.

<policies>
     <inbound>
        <base />
        <invoke-dapr-binding
                      name="external-system"
                      operation="create"
                      response-variable-name="bind-response">
            <metadata>
                <item key="source">api-management</item>
                <item key="client-ip">@( context.Request.IpAddress )</item>
            </metadata>
            <data>
                @( context.Request.Body.As<string>() )
            </data>
        </invoke-dapr-binding>
    </inbound>
    <backend>
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
        <return-response response-variable-name="bind-response" />
    </on-error>
</policies>

元素Elements

元素Element 说明Description 必需Required
invoke-dapr-bindinginvoke-dapr-binding Root 元素Root element Yes
metadatametadata 以键/值对的形式绑定特定的元数据。Binding specific metadata in the form of key/value pairs. 映射到 Dapr 中的元数据属性。Maps to the metadata property in Dapr. No
数据data 消息的内容。Content of the message. 映射到 Dapr 中的数据属性。Maps to the data property in Dapr. No

属性Attributes

属性Attribute 说明Description 必须Required 默认Default
namename 目标绑定名称。Target binding name. 必须与 Dapr 中的已定义的绑定名称匹配。Must match the name of the bindings defined in Dapr. Yes 不适用N/A
operationoperation 目标操作名称(特定于绑定)。Target operation name (binding specific). 映射到 Dapr 中的操作属性。Maps to the operation property in Dapr. No None
ignore-errorignore-error 如果设置为 true,则指示策略在收到来自 Dapr 运行时的错误时不触发“on error”部分If set to true instructs the policy not to trigger "on-error" section upon receiving error from Dapr runtime No false
response-variable-nameresponse-variable-name 用于存储来自 Dapr 运行时的响应的变量集合项的名称Name of the Variables collection entry to use for storing response from Dapr runtime No None
timeouttimeout 等待 Dapr 运行时做出响应的时间(以秒为单位)。Time (in seconds) to wait for Dapr runtime to respond. 范围为 1 到 240 秒。Can range from 1 to 240 seconds. No 55
templatetemplate 用于转换消息内容的模板引擎。Templating engine to use for transforming the message content. “Liquid”是唯一支持的值。"Liquid" is the only supported value. No None
content-typecontent-type 消息内容的类型。Type of the message content. “application/json”是唯一支持的值。"application/json" is the only supported value. No None

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站、出站、错误时Policy sections: inbound, outbound, on-error
  • 策略范围: 所有范围Policy scopes: all scopes