天天看點

面向.NET開發人員的Dapr——綁定

目錄:

  • 面向.NET開發人員的Dapr——前言
  • 面向.NET開發人員的Dapr——分布式世界
  • 面向.NET開發人員的Dapr——俯瞰Dapr
  • 面向.NET開發人員的Dapr——入門
  • 面向.NET開發人員的Dapr——參考應用程式
  • 面向.NET開發人員的Dapr——狀态管理
  • 面向.NET開發人員的Dapr——釋出和訂閱

The Dapr bindings building block

Dapr 綁定建構塊

Cloud-based serverless offerings, such as Azure Functions and AWS Lambda, have gained wide adoption across the distributed architecture space. Among many benefits, they enable a microservice to handle events from or invoke events in an external system - abstracting away the underlying complexity and plumbing concerns. External resources are many: They include datastores, message systems, and web resources, across different platforms and vendors. The Dapr bindings building block brings these same resource binding capabilities to the doorstep of your Dapr applications.

基于雲的 無服務産品(如 AZURE FUNCTIONS 和 AWS Lambda),在整個分布式體系結構領域獲得廣泛采用。在許多方面,它們使微服務能夠 處理來自 外部系統的事件或在外部系統 中調用事件 ,進而消除了底層複雜性和管道問題。外部資源很多:它們包括跨不同平台和供應商的資料存儲、消息系統和 web 資源。Dapr 綁定建構塊将這些資源綁定功能引入 Dapr 應用程式。

What it solves

解決方法

Dapr resource bindings enable your services to integrate business operations across external resources outside of the immediate application. An event from an external system could trigger an operation in your service passing in contextual information. Your service could then expand the operation by triggering an event in another external system, passing in contextual payload information. Your service communicates without coupling or awareness of the external resource. The plumbing is encapsulated inside pre-defined Dapr components. The Dapr component to use can be easily swapped at runtime without code changes.

通過 Dapr 資源綁定,服務可以将業務操作與應用程式之外的外部資源內建。來自外部系統的事件可能會觸發服務中的操作并傳遞上下文資訊。然後,你的服務可以通過在另一個外部系統中觸發事件來展開操作,同時傳遞上下文負載資訊。你的服務不需要耦合或知道外部資源就進行通信。該管道封裝在預定義的 Dapr 元件中。在運作時,可以輕松地替換 Dapr 元件,而無需更改代碼。

Consider, for example, a Twitter account that triggers an event whenever a user tweets a keyword. Your service exposes an event handler that receives and processes the tweet. Once complete, your service triggers an event that invokes an external Twilio service. Twilio sends an SMS message that includes the tweet. Figure 8-1 show the conceptual architecture of this operation.

考慮一下,當使用者推文時,Twitter 帳戶觸發事件 。服務公開用于接收和處理推文的事件處理程式。完成後,服務将觸發調用外部 Twilio 服務的事件。Twilio 發送包含推文的短信。圖8-1 顯示了此操作的概念體系結構。

面向.NET開發人員的Dapr——綁定

Figure 8-1. Conceptual architecture of a Dapr resource binding.

圖 8-1。Dapr 資源綁定的概念體系結構。

At first glance, resource binding behavior may appear similar to the Publish/Subscribe pattern described earlier in this book. While they share similarities, there are differences. Publish/subscribe focuses on asynchronous communication between Dapr services. Resource binding has a much wider scope. It focuses on system interoperability across software platforms. Exchanging information between disparate applications, datastores, and services outside your microservice application.

乍一看,資源綁定行為可能與本書前面介紹的 釋出/訂閱模式 類似。盡管它們有相似之處,但也有不同之處。釋出/訂閱側重于 Dapr services 之間的異步通信。資源綁定具有更大的範圍。它側重于軟體平台之間的系統互操作性。在不同的應用程式、資料存儲和微服務應用程式之外的服務之間交換資訊。

How it works

工作原理

Dapr resource binding starts with a component configuration file. This YAML file describes the type of resource to which you'll bind along with its configuration settings. Once configured, your service can receive events from the resource or trigger events on it.

通過元件配置檔案來使用Dapr 資源綁定。此 YAML 檔案描述綁定的資源類型。配置後,你的服務可以接收來自資源的事件或觸發事件。

Note

Binding configurations are presented in detail later in the Components section.

備注

稍後将在 " 元件 " 部分中詳細介紹綁定配置。

Input bindings

輸入綁定

Input bindings trigger your code with incoming events from external resources. To receive events and data, you register a public endpoint from your service that becomes the event handler. Figure 8-2 shows the flow:

輸入綁定通過外部資源的傳入事件觸發代碼。若要接收事件和資料,請在服務中注冊一個公共終結點作為 事件處理程式 。圖8-2 顯示了工作流:

面向.NET開發人員的Dapr——綁定

Figure 8-2. Dapr input binding flow.

圖 8-2。Dapr 輸入綁定流。

Figure 8.2 describes the steps for receiving events from an external Twitter account:

  1. The Dapr sidecar reads the binding configuration file and subscribes to the event specified for the external resource. In the example, the event source is a Twitter account.
  2. When a matching Tweet is published on Twitter, the binding component running in the Dapr sidecar picks it up and triggers an event.
  3. The Dapr sidecar invokes the endpoint (that is, event handler) configured for the binding. In the example, the service listens for an HTTP POST on the /tweet endpoint on port 6000. Because it's an HTTP POST operation, the JSON payload for the event is passed in the request body.
  4. After handling the event, the service returns an HTTP status code 200 OK.

圖8.2 介紹了從外部 Twitter 帳戶接收事件的步驟:

  1. Dapr 邊車讀取綁定配置檔案并訂閱外部資源特定的事件。在此示例中,事件源是一個 Twitter 帳戶。
  2. 當在 Twitter 上釋出了比對的推文時,在 Dapr 邊車中運作的綁定元件會捕捉到它并觸發一個事件。
  3. Dapr 邊車調用為綁定配置的終結點 (作為事件處理程式 ) 。在此示例中,服務監聽http://localhost:6000/tweet(POST)。由于它是 HTTP POST 操作,是以在請求正文中傳遞事件的 JSON 負載。
  4. 處理事件後,服務将傳回 HTTP  200 OK 狀态碼。

The following ASP.NET Core controller provides an example of handling an event triggered by the Twitter binding:

以下 ASP.NET Core 控制器提供了一個處理 Twitter 綁定觸發的事件的示例:

[ApiController]
public class SomeController : ControllerBase
{
public class TwitterTweet
    {
        [JsonPropertyName("id_str")]
public string ID {get; set; }

        [JsonPropertyName("text")]
public string Text {get; set; }
    }

    [HttpPost("/tweet")]
public ActionResult Post(TwitterTweet tweet)
    {
// Handle tweet
        Console.WriteLine("Tweet received: {0}: {1}", tweet.ID, tweet.Text);

// ...

// Acknowledge message
return Ok();
    }
}      

If the operation should error, you would return the appropriate 400 or 500 level HTTP status code. For bindings that feature at-least-once-delivery guarantees, the Dapr sidecar will retry the trigger. Check out [Dapr documentation for resource bindings][1] to see whether they offer at-least-once or exactly-once delivery guarantees.

如果操作錯誤,則會傳回相應的400或500級别的 HTTP 狀态碼。對于 至少傳遞一次 的綁定保證,Dapr 邊車将重試觸發。檢視 [有關資源綁定的 Dapr 文檔] [1],來檢視它們是否提供了 " 至少一次 " 或 "一次性傳遞 保證"。

Output bindings

輸出綁定

Dapr also includes output binding capabilities. They enable your service to trigger an event that invokes an external resource. Again, you start by configuring a binding configuration YAML file that describes the output binding. Once in place, you trigger an event that invokes the bindings API on the Dapr sidecar of your application. Figure 8-3 shows the flow of an output binding:

Dapr 還包括 輸出綁定 功能。它們使服務能夠觸發調用外部資源的事件。同樣,您首先配置描述輸出綁定的綁定配置 YAML 檔案。一旦準備好,可以觸發一個事件,該事件在應用程式的 Dapr 邊車上調用綁定 API。圖8-3 顯示了輸出綁定的工作流:

面向.NET開發人員的Dapr——綁定

Figure 8-3. Dapr output binding flow.

圖 8-3。Dapr 輸出綁定流。

  1. The Dapr sidecar reads the binding configuration file with the information on how to connect to the external resource. In the example, the external resource is a Twilio SMS account.
  2. Your application invokes the /v1.0/bindings/sms endpoint on the Dapr sidecar. In this case, it uses an HTTP POST to invoke the API. It's also possible to use gRPC.
  3. The binding component running in the Dapr sidecar calls the external messaging system to send the message. The message will contain the payload passed in the POST request.
  1. Dapr 邊車讀取綁定配置檔案,其中包含有關如何連接配接到外部資源的資訊。在此示例中,外部資源是 Twilio 的 SMS 帳戶。
  2. 應用程式調用Dapr 邊車上的 /v1.0/bindings/sms 終結點。此處,使用 HTTP POST 來調用 API。還可以使用 gRPC。
  3. 在 Dapr 邊車中運作的綁定元件會調用外部消息系統來發送消息。消息将包含 POST 請求中傳遞的負載。

As an example, you can invoke an output binding by invoking the Dapr API using curl:

例如,你可以通過使用curl調用 Dapr API 來調用輸出綁定:

curl -X POST http://localhost:3500/v1.0/bindings/sms \
  -H "Content-Type: application/json" \
-d '{
"data": "Welcome to this awesome service",
"metadata": {
"toNumber": "555-3277"
        },
"operation": "create"
      }'      

Note that the HTTP port is the same as used by the Dapr sidecar (in this case, the default Dapr HTTP port 3500).

請注意,HTTP 端口與 Dapr 邊車使用相同的端口 (在本例中為預設 Dapr HTTP 端口3500)  。

The structure of the payload (that is, message sent) will vary per binding. In the example above, the payload contains a data element with a message. Bindings to other types of external resources can be different, especially for the metadata that is sent. Each payload must also contain an operation field, that defines the operation the binding will execute. The above example specifies a create operation that creates the SMS message. Common operations include:

負載 (發送的消息) 的結構将因綁定而異。在上面的示例中,負載包含 data 元素。與其他類型的外部資源的綁定可能不同,尤其是中繼資料metadata 。每個負載還必須包含一個 operation 字段,該字段定義綁定将執行的操作。上面的示例指定了 create 操作以建立 SMS 消息。常見操作包括:

  • create
  • get
  • delete
  • list

It's up to the author of the binding which operations the binding supports. The documentation for each binding describes the available operations and how to invoke them.

取決于綁定支援的操作。每個綁定的文檔描述了可用的操作以及怎樣調用。

Using the Dapr .NET SDK

使用 Dapr .NET SDK

The Dapr .NET SDK provides language-specific support for .NET Core developers. In the following example, the call to the HttpClient.PostAsync() is replaced with the DaprClient.InvokeBindingAsync() method. This specialized method simplifies invoking a configured output binding:

Dapr .NET SDK 為 .NET Core 開發人員提供特定于語言的支援。在下面的示例中,對HttpClient.PostAsync()的調用被替換為對DaprClient.InvokeBindingAsync() 方法的調用。此專用方法簡化了調用已配置的輸出綁定:

private async Task SendSMSAsync([FromServices] DaprClient daprClient)
{
var message = "Welcome to this awesome service";
var metadata = new Dictionary<string, string>
    {
      { "toNumber", "555-3277" }
    };
await daprClient.InvokeBindingAsync("sms", "create", message, metadata);
}      

The method expects the metadata and message values.

此方法需要 metadata 和 message 值。

When used to invoke a binding, the DaprClient uses gRPC to call the Dapr API on the Dapr sidecar.

當用于調用綁定時,将 DaprClient 使用 gRPC 來調用 Dapr 邊車上的 DAPR API。

Binding components

綁定元件

Under the hood, resource bindings are implemented with Dapr binding components. They're contributed by the community and written in Go. If you need to integrate with an external resource for which no Dapr binding exists yet, you can create it yourself. Check out the Dapr components-contrib repo to see how you can contribute a binding.

在背景,資源綁定是通過 Dapr 綁定元件實作的。它們由社群提供,使用Go開發。如果需要與還沒有 Dapr 綁定的外部資源內建,可以自行建立。檢視 Dapr 元件-contrib 存儲庫,了解如何參與綁定。

Dapr and all of its components are written in the Golang (Go) language. Go is considered a modern, cloud-native programming platform.

Dapr 及其所有元件都是以 Go 語言編寫的。Go是現代的雲本地程式設計平台。

You configure bindings using a YAML configuration file. Here's an example configuration for the Twitter binding:

使用 YAML 配置檔案配置綁定。下面是用于 Twitter 綁定的示例配置:

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: twitter-mention
  namespace: default
spec:
  type: bindings.twitter
  version: v1
  metadata:
  - name: consumerKey
    value: "****" # twitter api consumer key, required
  - name: consumerSecret
    value: "****" # twitter api consumer secret, required
  - name: accessToken
    value: "****" # twitter api access token, required
  - name: accessSecret
    value: "****" # twitter api access secret, required
  - name: query
    value: "dapr" # your search query, required      

Each binding configuration contains a general metadata element with a name and namespace field. Dapr will determine the endpoint to invoke your service based upon the configured name field. In the above example, Dapr will invoke the method annotated with /twitter-mention in your service when an event occurs.

每個綁定配置都包含一個包含 metadata 元素和name、namespace 字段。Dapr 将根據配置的name 字段确定要調用服務的終結點。在上面的示例中,Dapr 将在事件發生時調用在服務中(使用 /twitter-mention 批注)的方法。

In the spec element, you specify the type of the binding along with binding specific metadata. The example specifies credentials for accessing a Twitter account using its API. The metadata can differ between input and output bindings. For example, to use Twitter as an input binding, you need to specify the text to search for in tweets using the query field. Every time a matching tweet is sent, the Dapr sidecar will invoke the /twitter-mention endpoint on the service. It will also deliver the contents of the tweet.

在 spec 元素中,指定綁定的 type 和綁定特定的 metadata 。該示例指定了用于通路 Twitter 帳戶的憑據,用于将來通路推特的api。輸入綁定和輸出綁定的中繼資料可以不同。例如,若要使用 Twitter 作為輸入綁定,需要使用query 字段指定要在推文中搜尋的文本 。每次發送比對的推文時,Dapr 邊車将調用服務上的 /twitter-mention 終結點。它還将傳遞推文的内容。

A binding can be configured for input, output, or both. Interestingly, the binding doesn't explicitly specify input or output configuration. Instead, the direction is inferred by the usage of the binding along with configuration values.

可以将綁定配置為用于輸入和/或輸出。有趣的是,綁定未顯式指定輸入或輸出配置。相反,通過使用綁定以及配置值進行推斷方向。

The [Dapr documentation for resource bindings][1] provides a complete list of the available bindings and their specific configuration settings.

[資源綁定的 Dapr 文檔] [1] 提供了可用綁定的完整清單及其特定的配置設定。

Cron binding

Cron 綁定

Pay close attention to Dapr's Cron binding. It doesn't subscribe to events from an external system. Instead, this binding uses a configurable interval schedule to trigger your application. The binding provides a simple way to implement a background worker to wake up and do some work at a regular interval, without the need to implement an endless loop with a configurable delay. Here's an example of a Cron binding configuration:

請密切注意 Dapr 的 Cron 綁定。它不訂閱外部系統中的事件。相反,此綁定使用可配置的間隔計劃來觸發你的應用程式。綁定提供了一種簡單的途徑來實作背景工作線程喚醒,并定期執行一些工作,而無需實作具有可配置延遲的無限循環。下面是 Cron 綁定配置的示例:

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: checkOrderBacklog
  namespace: default
spec:
  type: bindings.cron
  version: v1
  metadata:
  - name: schedule
    value: "@every 30m"      

In this example, Dapr triggers a service by invoking the /checkOrderBacklog endpoint every 30 minutes. There are several patterns available for specifying the schedule value. For more information, see the Cron binding documentation.

在此示例中,Dapr 通過每隔30分鐘調用 /checkOrderBacklog 終結點來觸發服務。有多種可用于指定 schedule 值的模式。有關詳細資訊,請參閱 Cron 綁定文檔。

Reference application: eShopOnDapr

參考應用程式:eShopOnDapr

The accompanying eShopOnDapr reference application implements an output binding example. It triggers the Dapr SendGrid binding to send a user an email when a new order is placed. You can find this binding in the eshop-email.yaml file in the components folder:

随附的 eShopOnDapr 參考應用程式實作了輸出綁定示例。它觸發 Dapr SendGrid 綁定,以便在有新訂單時向使用者發送電子郵件。可以在 components 檔案夾的 eshop-email.yaml 檔案中找到此綁定:

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: sendmail
  namespace: eshop
spec:
  type: bindings.twilio.sendgrid
  version: v1
  metadata:
  - name: apiKey
    secretKeyRef:
      name: sendGridAPIKey
auth:
  secretStore: eshop-secretstore      

This configuration uses the Twilio SendGrid binding component. Note how the API key for connecting to the service consumes a Dapr secret reference. This approach keeps secrets outside of the configuration file. Read the secrets building block chapter to learn more about Dapr secrets.

此配置使用 Twilio SendGrid 綁定元件。請注意,用于連接配接到服務的 API 密鑰怎樣使用 Dapr 機密引用。此方法在配置檔案之外儲存機密。請參閱 機密建構塊章節 ,詳細了解 Dapr 機密。

The binding configuration specifies a binding component that can be invoked using the /sendmail endpoint on the Dapr sidecar. Here's a code snippet in which an email is sent whenever an order is started:

綁定配置指定一個綁定元件,該元件可使用Dapr 邊車上的 /sendmail 終結點進行調用。以下代碼片段将在每次有新訂單時發送電子郵件:

public Task Handle(OrderStartedDomainEvent notification, CancellationToken cancellationToken)
{
var string message = CreateEmailBody(notification);
var metadata = new Dictionary<string, string>
    {
        {"emailFrom", "[email protected]"},
        {"emailTo", notification.UserName},
        {"subject", $"Your eShopOnDapr order #{notification.Order.Id}"}
    };
return _daprClient.InvokeBindingAsync("sendmail", "create", message, metadata, cancellationToken);
}      

As you can see in this example, message contains the message body. The CreateEmailBody method simply formats a string with the body text. The metadata specifies the email sender, recipient, and the subject for the email message. If these values are static, they can also be included in the metadata fields in the configuration file. The name of the binding to invoke is sendmail and the operation is create.

如本示例中所示, message 包含消息正文。 CreateEmailBody方法隻是将字元串轉換為正文文本。 metadata 指定電子郵件發件人、收件人和電子郵件的主題。如果這些值是靜态的,則也可以将它們包含在配置檔案的中繼資料字段中。要調用的綁定的名稱為 sendmail ,并且操作為 create 。

Summary

總結

Dapr resource bindings enable you to integrate with different external resources and systems without taking dependencies on their libraries or SDKs. These external systems don't necessarily have to be messaging systems like a service bus or message broker. Bindings also exist for datastores and web resources like Twitter or SendGrid.

Dapr 資源綁定允許你內建不同的外部資源和系統,而無需依賴于這些外部資源和系統的庫或 Sdk。這些外部系統不一定必須是消息傳遞系統,例如服務總線或消息代理。資料存儲和 web 資源(如 Twitter 或 SendGrid)也可用來綁定。

Input bindings (or triggers) react to events occurring in an external system. They invoke the public HTTP endpoints pre-configured in your application. Dapr uses the name of the binding in the configuration to determine the endpoint to call in your application.

輸入綁定 (或觸發器) 對外部系統中發生的事件做出響應。它們調用在你的應用程式中預先配置的公共 HTTP 終結點。Dapr 使用配置中的綁定名稱來确定要在應用程式中調用的終結點。

Output bindings will send messages to an external system. You trigger an output binding by doing an HTTP POST on the /v1.0/bindings/<binding-name> endpoint on the Dapr sidecar. You can also use gRPC to invoke the binding. The .NET SDK offers a InvokeBindingAsync method to invoke Dapr bindings using gRPC.

繼續閱讀