The documentation you are viewing is for Dapr v1.7 which is an older version of Dapr. For up-to-date documentation, see the latest version.

使用输出绑定调用不同的资源

使用 Dapr 输出绑定调用外部系统

使用绑定,可以调用外部资源,而无需绑定到特定的 SDK 或库。 有关显示输出绑定的完整示例,请访问此 链接

观看如何使用双向输出绑定的 视频

1. 1. 创建绑定

输出绑定表示 Dapr 将使用调用和向其发送消息的资源。

就本指南的目的,您将使用 Kafka 绑定。 You can find a list of the different binding specs here.

创建一个新的名称为 myevent 的绑定组件。

metadata 部分中,配置 Kafka 相关属性,如要将消息发布到其的topics和代理。


创建以下 YAML 文件,名为 binding.yaml,并将其保存到应用程序的 components 子文件夹中。 (使用具有 --components-path 标记 的 dapr run 命令来指向自定义组件目录)

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: myevent
  namespace: default
spec:
  type: bindings.kafka
  version: v1
  metadata:
  - name: brokers
    value: localhost:9092
  - name: publishTopic
    value: topic1

To deploy this into a Kubernetes cluster, fill in the metadata connection details of your desired binding component in the yaml below (in this case kafka), save as binding.yaml, and run kubectl apply -f binding.yaml.

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: myevent
  namespace: default
spec:
  type: bindings.kafka
  version: v1
  metadata:
  - name: brokers
    value: localhost:9092
  - name: publishTopic
    value: topic1

2. 2. 发送事件

注: 在 Kubernetes 中运行时,使用 kubectl apply -f binding.yaml 将此文件应用于您的集群

您可以使用 HTTP 来这样做:

curl -X POST -H 'Content-Type: application/json' http://localhost:3500/v1.0/bindings/myevent -d '{ "data": { "message": "Hi!" }, "operation": "create" }'

如上文所见,您使用了要调用的绑定的名称来调用 /binding 终结点。 在我们的示例中,它的名称是 myevent 。 有效载荷位于必需的 data 字段中,并且可以是任何 JSON 可序列化的值。

您还会注意到,有一个 operation 字段告诉绑定您需要它执行的操作。 You can check here which operations are supported for every output binding.

参考资料