天天看點

面向.NET開發人員的Dapr——入門

目錄:

  • 面向.NET開發人員的Dapr——前言
  • 面向.NET開發人員的Dapr——分布式世界
  • 面向.NET開發人員的Dapr——俯瞰Dapr

Get started with Dapr

Dapr 入門

In the first two chapters, you learned basic concepts about Dapr. It's time to take it for a test drive. This chapter will guide you through preparing your local development environment and building two Dapr .NET applications.

前兩章介紹了有關 Dapr 的基本概念。現在實操一下。本章将指導你完成本地開發環境的準備工作,并建構兩個 Dapr .NET 應用程式。

Install Dapr into your local environment

将 Dapr 安裝到本地環境中

You'll start by installing Dapr on your development computer. Once complete, you can build and run Dapr applications in self-hosted mode.

  1. Install the Dapr CLI. It enables you to launch, run, and manage Dapr instances. It also provides debugging support.
  2. Install Docker Desktop. If you're running on Windows, make sure that Docker Desktop for Windows is configured to use Linux containers.

首先,在開發計算機上安裝 Dapr。完成後,可以在 自承載模式下建構并運作 Dapr 應用程式。

  1. 安裝 DAPR CLI。它使您可以啟動、運作和管理 Dapr 執行個體。它還提供調試支援。
  2. 安裝 Docker Desktop。如果在 Windows 上運作,請確定将 适用于 windows 的 Docker Desktop 配置為使用 Linux 容器。

Note

By default, Dapr uses Docker containers to provide you the best out-of-the-box experience. To run Dapr outside of Docker, you can skip this step and execute a slim initialization. The examples in this chapter require you use Docker containers.

備注

預設情況下,Dapr 使用 Docker 容器為你提供最佳的開箱即用體驗。若要在 Docker 外部運作 Dapr,可以跳過此步驟并 執行至簡初始化。本章中的示例要求使用 Docker 容器。

  1. Initialize Dapr. This step sets up your development environment by installing the latest Dapr binaries and container images.
  2. Install the .NET Core 3.1 SDK.
  1. 初始化 Dapr。此步驟通過安裝最新的 Dapr 二進制檔案和容器映像來設定開發環境。
  2. 安裝 .NET Core 3.1 SDK。

Now that Dapr is installed, it's time to build your first Dapr application!

安裝 Dapr 後,就可以建構你的第一個 Dapr 應用程式了!

Build your first Dapr application

建構第一個 Dapr 應用程式

You'll start by building a simple .NET Console application that consumes the Dapr state management building block.

首先,你将建構一個簡單的 .NET 控制台應用程式,該應用程式使用 Dapr 狀态管理 建構塊。

Create the application

建立應用程式

  1. Open up the command shell or terminal of your choice. You might consider the terminal capabilities in Visual Studio Code. Navigate to the root folder in which you want to build your application. Once there, enter the following command to create a new .NET Console application:       打開指令行終端。可以考慮使用Visual Studio Code中的終端。 導航到要建構應用程式的根檔案夾。完成後,輸入以下指令以建立新的 .NET 控制台應用程式:
    dotnet new console -o DaprCounter      
    The command scaffolds a simple "Hello World" .NET Core application.      該指令搭建簡單的"Hello World“.NET Core 應用程式。
  2. Then, navigate into the new directory created by the previous command:      然後,定位到上一指令建立的新目錄:
    cd DaprCounter      
  3. Run the newly created application using the dotnet run command. Doing so writes "Hello World!" to the console screen:      使用 dotnet run 指令運作新建立的應用程式。這樣做會在控制台螢幕上輸出"Hello World!" :
dotnet run      

Add Dapr State Management

添加 Dapr 狀态管理

Next, you'll use the Dapr state management building block to implement a stateful counter in the program.

接下來,你将使用 Dapr 狀态管理建構塊 在程式中實作有狀态計數器。

You can invoke Dapr APIs across any development platform using Dapr's native support for HTTP and gRPC. However, .NET Developers will find the Dapr .NET SDK more natural and intuitive. It provides a strongly typed .NET client to call the Dapr APIs. The .NET SDK also tightly integrates with ASP.NET Core.      可以使用 Dapr 對 HTTP 和 gRPC 的本機支援跨任何開發平台調用 Dapr API。然而,.NET 開發者會發現 Dapr .NET SDK 更自然、更直覺。它提供強類型的 .NET 用戶端來調用 Dapr API。.NET SDK 還與 ASP.NET Core 緊密內建。

  1. From the terminal window, add the Dapr.Client NuGet package to your application:      在終端視窗中,将 Dapr.Client 的NuGet 包添加到應用程式:
    dotnet add package Dapr.Client      

    If you're working with a pre-release version of Dapr, be sure to add the --prerelease flag to the command.

    如果使用 Dapr 的預發行版本,請確定在指令中添加 --prerelease 标志。

  2. Open the Program.cs file in your favorite editor and update its contents to the following code:      在你喜歡的編輯器中打開  Program.cs 檔案,将其内容更新為以下代碼:
    using System;
    using System.Threading.Tasks;
    using Dapr.Client;
    
    namespace DaprCounter
    {
    class Program
        {
    static async Task Main(string[] args)
            {
    const string storeName = "statestore";
    const string key = "counter";
    
    var daprClient = new DaprClientBuilder().Build();
    var counter = await daprClient.GetStateAsync<int>(storeName, key);
    
    while (true)
                {
                    Console.WriteLine($"Counter = {counter++}");
    
    await daprClient.SaveStateAsync(storeName, key, counter);
    await Task.Delay(1000);
                }
            }
        }
    }      
    The updated code implements the following steps:      更新的代碼實作以下步驟:
  • First a new DaprClient instance is instantiated. This class enables you to interact with the Dapr sidecar.      首先執行個體化一個 DaprClient 新執行個體。此類使你可以與 Dapr 邊車互動。
  • From the state store, DaprClient.GetStateAsync fetches the value for the counter key. If the key doesn't exist, the default int value (which is 0) is returned.      DaprClient.GetStateAsync 從狀态存儲中擷取counter鍵對應的值 。如果該鍵不存在,傳回預設的整數值0。
  • The code then iterates, writing the counter value to the console and saving an incremented value to the state store.      然後,代碼将在控制台上循環輸出計數器值,并将遞增的值儲存到狀态存儲中。
  • The Dapr CLI run command starts the application. It invokes the underlying Dapr runtime and enables both the application and Dapr sidecar to run together. If you omit the app-id, Dapr will generate a unique name for the application. The final segment of the command, dotnet run, instructs the Dapr runtime to run the .NET core application.       使用Dapr CLI run 指令啟動應用程式。它調用底層 Dapr 運作時,并使應用程式和 Dapr 邊車一起運作。如果省略 app-id參數,則 Dapr 将為應用程式生成唯一的名稱。指令的最後一段 dotnet run 訓示 Dapr 運作時運作 .net core 應用程式。

    Important

    Care must be taken to always pass an explicit app-id parameter when consuming the state management building block. The block uses the application id value as a prefix for its state key for each key/value pair. If the application id changes, you can no longer access the previously stored state.

    重要

    使用狀态管理建構塊時,必須注意始終顯式傳遞app-id參數。對于每個鍵/值對,狀态管理建構塊使用應用程式 id 值作為其狀态鍵的 字首 。如果應用程式 id 發生更改,則無法再通路以前存儲的狀态。

    Now run the application with the following command:      現在,用以下指令運作應用程式:

    dapr run --app-id DaprCounter dotnet run      
    Try stopping and restarting the application. You'll see that the counter doesn't reset. Instead it continues from the previously saved state. The Dapr building block makes the application stateful.

             嘗試停止并重新啟動應用程式。你将看到計數器未被重置。相反,它會從以前儲存的狀态繼續。Dapr 建構塊會使應用程式具有狀态。

It's important to understand your sample application communicates with a pre-configured state component, but has no direct dependency on it. Dapr abstracts away the dependency. As you'll shortly see, the underlying state store component can be changed with a simple configuration update.

務必了解你的示例應用程式與預配置狀态元件的通信,但沒有直接依賴它。Dapr 消除依賴關系。如你稍後所見,可以通過簡單的配置更新來替換底層狀态存儲元件。

You might be wondering, where exactly is the state stored?

你可能想知道狀态存儲在何處?

Component configuration files

元件配置檔案

When you first initialized Dapr for your local environment, it automatically provisioned a Redis container. Dapr then configured the Redis container as the default state store component with a component configuration file, entitled statestore.yaml. Here's a look at its contents:

首次為本地環境初始化 Dapr 時,會自動預配 Redis 容器。然後,Dapr 使用名為  statestore.yaml 的元件配置檔案将 Redis 容器配置為預設狀态存儲元件。下面檢視其内容:

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: statestore
spec:
  type: state.redis
  version: v1
  metadata:
  - name: redisHost
    value: localhost:6379
  - name: redisPassword
    value: ""
  - name: actorStateStore
    value: "true"      

Default component configuration files are stored in the $HOME/.dapr/components folder on Linux/macOS, and in the %USERPROFILE%\.dapr\components folder on Windows.

預設元件配置檔案存儲在 Linux/macOS 上的 $HOME/.dapr/components檔案夾中,Windows 上的 %USERPROFILE%\.dapr\components 檔案夾中。

Note the format of the previous component configuration file:

  • Each component has a name. In the sample above, the component is named statestore. We used that name in our first code example to tell the Dapr sidecar which component to use.
  • Each component configuration file has a spec section. It contains a type field that specifies the component type. The version field specifies the component version. The metadata field contains information that the component requires, such as connection details and other settings. The metadata values will vary for the different types of components.

請注意上一個元件配置檔案的格式:

  • 每個元件都有一個名稱。在以上示例中,元件名為 statestore 。我們在第一個代碼示例中使用了該名稱來告知 Dapr 邊車要使用哪個元件。
  • 每個元件配置檔案都有一個 spec節。它包含一個指定元件類型的 type 字段。 version字段指定元件版本。 metadata字段包含元件的必要資訊,例如連接配接詳細資訊和其他設定。中繼資料值因不同類型的元件而異。

A Dapr sidecar can consume any Dapr component configured in your application. But, what if you had an architectural justification to limit the accessibility of a component? How could you restrict the Redis component to Dapr sidecars running only in a production environment?

Dapr 邊車可以使用應用程式中配置的任何 Dapr 元件。但是,假如有構造的正當理由限制元件的可通路性,該怎麼辦呢?如何限制僅在生産環境中運作的Dapr 邊車上使用 Redis 元件呢?

To do so, you could define a namespace for the production environment. You might name it production. In self-hosted mode, you specify the namespace of a Dapr sidecar by setting the NAMESPACE environment variable. When configured, the Dapr sidecar will only load the components that match the namespace. For Kubernetes deployments, the Kubernetes namespace determines the components that are loaded. The following sample shows the Redis component placed in a production namespace. Note the namespace declaration in the metadata element:

為此,可以為生産環境定義一個命名空間。可以将其命名為 production 。在自承載模式下,通過設定 NAMESPACE環境變量來指定 Dapr 邊車的命名空間 。配置後,Dapr 邊車将僅加載與該命名空間比對的元件。對于 Kubernetes 部署,Kubernetes 命名空間決定加載的元件。下面的示例示範 production命名空間中的 Redis 元件 。請注意 metadata 元素中的namespace 聲明 :

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: statestore
  namespace: production
spec:
  type: state.redis
  version: v1
  metadata:
  - name: redisHost
    value: localhost:6379
  - name: redisPassword
    value: ""
  - name: actorStateStore
    value: "true"      

A namespaced component is only accessible to applications running in the same namespace. If your Dapr application fails to load a component, make sure that the application namespace matches the component namespace. This can be especially tricky in self-hosted mode where the application namespace is stored in a NAMESPACE environment variable.

隻有在同一命名空間中運作的應用程式才能通路帶命名空間元件。如果 Dapr 應用程式無法加載元件,請確定應用程式命名空間與元件命名空間相比對。在自承載模式下要注意的一點是:應用程式命名空間存儲于 NAMESPACE 環境變量中(不知怎麼翻譯合适)。

If needed, you could further restrict a component to a particular application. Within the production namespace, you may want to limit access of the Redis cache to only the DaprCounter application. You do so by specifying scopes in the component configuration. The following example shows how to restrict access to the Redis statestore component to the application DaprCounter in the production namespace:

如果需要,可以進一步将元件限制到特定的應用程式。在 production 命名空間中,你可能需要将 Redis 緩存的通路限制為僅限 DaprCounter 應用程式。為此,請在元件配置中指定 scopes 。下面的示例示範如何将對 Redis 狀态存儲元件的通路限制 到 production 命名空間中的應用程式 DaprCounter :

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: statestore
  namespace: production
spec:
  type: state.redis
  version: v1
  metadata:
  - name: redisHost
    value: localhost:6379
  - name: redisPassword
    value: ""
  - name: actorStateStore
    value: "true"
  scopes:
  - DaprCounter       

Build a multi-container Dapr application

建構多容器 Dapr 應用程式

In the first example, you created a simple .NET console application that ran side-by-side with a Dapr sidecar. Modern distributed applications, however, often consist of many moving parts. They can simultaneously run independent microservices. These modern applications are typically containerized and require container orchestration tools such as Docker Compose or Kubernetes.

在第一個示例中,建立了一個與 Dapr 邊車并行運作的簡單 .NET 控制台應用程式。不過,現代分布式應用程式通常由許多移動部件組成。它們可以同時運作,不依賴于微服務。這些現代應用程式通常容器化,并需要容器編排工具,例如 Docker Compose 或 Kubernetes。

In the next example, you'll create a multi-container application. You'll also use the Dapr service invocation building block to communicate between services. The solution will consist of a web application that retrieves weather forecasts from a web API. They will each run in a Docker container. You'll use Docker Compose to run the container locally and enable debugging capabilities.

在下一個示例中,将建立多容器應用程式。你還将使用 Dapr 服務調用 建構塊在服務之間進行通信。該解決方案将包含一個從 Web API 檢索天氣預報的 Web 應用程式。它們在 各自的Docker 容器中運作。你将使用 Docker Compose在本地運作容器并啟用調試功能。

Make sure you've configured your local environment for Dapr and installed the .NET Core 3.1 Development Tools (instructions are available at the beginning of this chapter).

請確定為 Dapr 配置了本地環境并安裝了 .NET Core 3.1 開發工具 (請參閱本章開頭部分) 。

Additionally, you'll need complete this sample using Visual Studio 2019 with the .NET Core cross-platform development workload installed.

此外,需要在安裝了 .NET Core 跨平台開發工作負載的 Visual Studio 2019中完成此示例。

  1. In Visual Studio 2019, create an ASP.NET Core Web App project:      在 Visual Studio 2019 中,建立ASP.NET Core Web 應用項目 :
    面向.NET開發人員的Dapr——入門
  2. Name your project DaprFrontEnd and your solution DaprMultiContainer:      項目命名為 DaprFrontEnd ,解決方案命名為 DaprMultiContainer :
    面向.NET開發人員的Dapr——入門
  3. Select Web Application to create a web application with Razor pages. Don't select Enable Docker Support. You'll add Docker support later.      選擇“Web 應用程式”,建立使用 Razor Pages 的 Web 應用程式 。請勿選擇"啟用 Docker 支援"。 稍後添加 Docker 支援。
    面向.NET開發人員的Dapr——入門
  4. Add a ASP.NET Core Web API project to the same solution and call it DaprBackEnd. Select API as the project type. By default, a Dapr sidecar relies on the network boundary to limit access to its public API. So, clear the checkbox for Configure for HTTPS.      在解決方案中添加 ASP.NET Core Web API 項目,并命名為 DaprBackEnd。選擇 "API" 作為項目類型。預設情況下,Dapr 邊車依賴于網絡邊界來限制對公共 API 的通路。是以,請清除"為 HTTPS 配置"複選框。
    面向.NET開發人員的Dapr——入門

Add Dapr service invocation

添加 Dapr 服務調用

Now, you'll configure communication between the services using Dapr service invocation building block. You'll enable the web app to retrieve weather forecasts from the web API. The service invocation building block features many benefits. It includes service discovery, automatic retries, message encryption (using mTLS), and improved observability. You'll use the Dapr .NET SDK to invoke the service invocation API on the Dapr sidecar.

現在,你将使用 Dapr 服務調用建構基塊 配置服務 之間的通信。你将允許 Web 應用從 Web API 檢索天氣預報。服務調用建構基塊具有許多優點。它包括服務發現、自動重試、 (使用 mTLS) 的消息加密,并改進了可觀察性。你将使用 Dapr .NET SDK 調用 Dapr 邊車上的服務調用 API。

  1. In Visual Studio, open the Package Manager Console (Tools > NuGet Package Manager > Package Manager Console) and make sure that DaprFrontEnd is the default project. From the console, add the Dapr.AspNetCore NuGet package to the project:      在 Visual Studio 中,打開包管理器控制台 (工具 > "NuGet 包管理器" > 程式包管理器控制台) ,并確定這 DaprFrontEnd 是預設項目。從控制台中,将 Dapr.AspNetCore NuGet 包添加到項目:
    Install-Package Dapr.AspNetCore      

    If you're targeting a version of Dapr.AspNetCore that is in prerelease, you need to specify the -Prerelease flag.

    如果要以 Dapr.AspNetCore 的預發行版本為目标,則需要指定 -Prerelease 标志。

  2. In the DaprFrontEnd project, open the Startup.cs file, and replace the ConfigureServices method with the following code:      在 DaprFrontEnd 項目中,打開 Startup.cs 檔案,并将 ConfigureServices 方法替換為以下代碼:
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers().AddDapr();
        services.AddRazorPages();
    }      
    The call to AddDapr registers the DaprClient class with the ASP.NET Core dependency injection system. With the client registered, you can now inject an instance of DaprClient into your service code to communicate with the Dapr sidecar, building blocks, and components.      對 AddDapr 的調用會将DaprClient 類注冊到 ASP.NET Core 依賴關系注入系統。在注冊用戶端的情況下,你現在可以将DaprClient 的執行個體注入到你的服務代碼中,以便與 Dapr邊車、建構塊群組件通信。
  3. Add a new C# class file named WeatherForecast to the DaprFrontEnd project:      将名為 WeatherForecast 的新 c # 類檔案添加到 DaprFrontEnd 項目:
    using System;
    
    namespace DaprFrontEnd
    {
    public class WeatherForecast
        {
    public DateTime Date { get; set; }
    
    public int TemperatureC { get; set; }
    
    public int TemperatureF { get; set; }
    
    public string Summary { get; set; }
        }
    }       
  4. Open the Index.cshtml.cs file in the Pages folder, and replace its contents with the following code:      打開 Pages 檔案夾中 的 Index.cshtml.cs 檔案,然後将其 内容替換為以下代碼:
    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Threading.Tasks;
    using Dapr.Client;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace DaprFrontEnd.Pages
    {
    public class IndexModel : PageModel
        {
    private readonly DaprClient _daprClient;
    
    public IndexModel(DaprClient daprClient)
            {
                _daprClient = daprClient ?? throw new ArgumentNullException(nameof(daprClient));
            }
    
    public async Task OnGet()
            {
    var forecasts = await _daprClient.InvokeMethodAsync<IEnumerable<WeatherForecast>>(
                    HttpMethod.Get,
    "daprbackend",
    "weatherforecast");
    
                ViewData["WeatherForecastData"] = forecasts;
            }
        }
    }      
    You add Dapr capabilities into the web app by injecting the DaprClient class into IndexModel constructor. In the OnGet method, you call the API service with the Dapr service invocation building block. The OnGet method is invoked whenever a user visits the home page. You use the DaprClient.InvokeMethodAsync method to invoke the weatherforecast method of the daprbackend service. You'll configure the web API to use daprbackend as its application ID later on when configuring it to run with Dapr. Finally, the service response is saved in view data.      通過将DaprClient 類注入IndexModel 的構造函數,可将 Dapr 功能添加到 web 應用中 。在 OnGet 方法中,通過 Dapr 服務調用建構塊來調用 Web API 服務Daprbackend。 每當使用者通路首頁時,都會調用OnGet方法。使用 DaprClient.InvokeMethodAsync 方法來調用daprbackend 服務的 weatherforecast 方法 。稍後,将 web API 配置為使用Dapr,并将其應用程式Id設定為daprbackend。最後,将服務響應儲存在ViewData中。
  5. Replace the contents of the Index.cshtml file in the Pages folder, with the following code. It displays the weather forecasts stored in the view data to the user:      用以下代碼替換 Pages 檔案夾中的Index.cshtml 檔案的内容。它會将ViewData中存儲的天氣預報顯示給使用者:
@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    @foreach (var forecast in (IEnumerable<WeatherForecast>)ViewData["WeatherForecastData"])
    {
<p>The forecast for @forecast.Date is @forecast.Summary!</p>
    }
</div>      

Add container support

添加容器支援

In the final part of this example, you'll add container support and run the solution using Docker Compose.

最後,你将添加容器支援,并使用 Docker Compose 運作解決方案。

  1. Right-click the DaprFrontEnd project, and choose Add > Container Orchestrator Support. The Add Container Orchestrator Support dialog appears:      右擊 DaprFrontEnd 項目,然後選擇 "添加 > 容器編排支援"。将顯示 "添加容器編排支援 "對話框:
    面向.NET開發人員的Dapr——入門
    Choose Docker Compose.      選擇“Docker Compose”。
  2. In the next dialog, select Linux as the Target OS:      下一個對話框中,選擇 "Linux" 作為"目标 OS":
    面向.NET開發人員的Dapr——入門
    Visual Studio creates a docker-compose.ymlfile and a .dockerignore file in the docker-compose folder in the solution:      Visual Studio在解決方案中的 docker-compose 檔案夾中建立 docker-compose.yml 檔案和 .dockerignore 檔案:
    面向.NET開發人員的Dapr——入門
    The docker-compose.yml file has the following content:      docker-compose.yml 檔案包含以下内容(不太清楚DOCKER_REGISTRY,它可能是表示docker注冊中心的環境變量,如果沒有設定此環境變量,則使用預設值(空字元串),待驗證;image指令指定使用的鏡像名稱(和标簽),context指令指定dockerfile檔案所在的目錄或一個git倉庫,它可以是一個相對路徑(相對于docker-compose.yml),dockerfile指定dockerfile檔案(相對于context指定的路徑)):
    version: "3.4"
    
    services:
      daprfrontend:
        image: ${DOCKER_REGISTRY-}daprfrontend
        build:
          context: .
          dockerfile: DaprFrontEnd/Dockerfile      

    The .dockerignore file contains file types and extensions that you don't want Docker to include in the container. These files are associated with the development environment and source control and not the app or service you're deploying.      .dockerignore 檔案包含你不希望 在Docker容器中包含的檔案類型和擴充名。這些檔案與開發環境和源代碼管理相關聯,而不是與要部署的應用或服務相關聯。

    In the root of the DaprFrontEnd project directory, a new Dockerfile was created. A Dockerfile is a sequence of commands that are used to build an image. For more information, see Dockerfile reference.      在 DaprFrontEnd 項目的根目錄中,建立了一個新的 Dockerfile。 Dockerfile 是一系列用于生成鏡像的指令。有關詳細資訊,請參閱 Dockerfile 參考。

    The Dockerfile contains the YAML:      Dockerfile 包含如下内容:

    FROM mcr.microsoft.com/dotnet/aspnet:3.1 AS base
    WORKDIR /app
    EXPOSE 80
    EXPOSE 443
    
    FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
    WORKDIR /src
    COPY ["DaprFrontEnd/DaprFrontEnd.csproj", "DaprFrontEnd/"]
    RUN dotnet restore "DaprFrontEnd/DaprFrontEnd.csproj"
    COPY . .
    WORKDIR "/src/DaprFrontEnd"
    RUN dotnet build "DaprFrontEnd.csproj" -c Release -o /app/build
    
    FROM build AS publish
    RUN dotnet publish "DaprFrontEnd.csproj" -c Release -o /app/publish
    
    FROM base AS final
    WORKDIR /app
    COPY --from=publish /app/publish .
    ENTRYPOINT ["dotnet", "DaprFrontEnd.dll"]      
    The preceding Dockerfile sequentially performs the following steps when invoked:      在調用上面 Dockerfile 時按順序執行以下步驟(此處用到了docker的多階段建構方式,最後生成的鏡像,以最後一條 FROM 為準,之前的 FROM作為中間階段将會被抛棄):
  • Targeting the Release configuration and outputs to /app/publish.      将釋出配置和輸出定位到 /app/publish。
  • Targeting the Release configuration and outputs to /app/build.      将 釋出配置和輸出定位到 /app/build。
  1. Pulls the mcr.microsoft.com/dotnet/aspnet:3.1 image and names it base.      拉取 mcr.microsoft.com/dotnet/aspnet:3.1 鏡像,将其命名為 base 。
  2. Sets the working directory to /app.      将工作目錄設定為 /app。WORKDIR指令指定後續指令的工作目錄
  3. Exposes port 80 and 443.      聲明視窗要公開 80 端口和 443端口,這些端口都是容器内部端口,非宿主端口 。
  4. Pulls the mcr.microsoft.com/dotnet/sdk:3.1 image and names it build.      拉取 mcr.microsoft.com/dotnet/sdk:3.1 鏡像,将其命名為 build 。
  5. Sets the working directory to /src.      将工作目錄設定為 /src。
  6. Copies the DaprFrontEnd/DaprFrontEnd.csproj to a new directory named DaprFrontEnd/.      将 DaprFrontEnd/DaprFrontEnd.csproj 複制到名為 DaprFrontEnd/ 的新目錄。COPY指令将Dockerfile所在目錄中的檔案拷貝到鏡像中
  7. Calls dotnet restore on the project.      對項目調用 dotnet restore  。
  8. Copies everything from the root directory into the image's root.      将根目錄中的所有内容複制到鏡像的根目錄中。
  9. Sets the working directory to /src/DaprFrontEnd.      将工作目錄設定為 /src/DaprFrontEnd。
  10. Calls dotnet build on the project.      對該項目調用 dotnet build 
  11. Initializes a new build stage from the existing build base image and names it publish.      從現有build鏡像初始化新的建構階段并命名為 publish 。
  12. Calls dotnet publish on the project.      對項目調用 dotnet publish。
  13. Initializes a new build stage from the existing publish base image and names it final.      從現有base鏡像初始化新的建構階段并命名為 final 。
  14. Sets the working directory to /app.      将工作目錄設定為 /app。
  15. Copies the /app/publish directory from the publish image into the root of the final image.     從publish 鏡像将 /app/publish 目錄複制到final鏡像的根目錄 。
  16. Sets the entry point as the image to dotnet and passes the DaprFrontEnd.dll as an arg.      設定鏡像的入口點為dotnet,并将 DaprFrontEnd.dll 作為參數傳遞。
  • In the DaprBackEnd web API project, right-click on the project node, and choose Add > Container Orchestrator Support. Choose Docker Compose, and then select Linux again as the target OS.      在 DaprBackEnd web API 項目中,右擊項目,然後選擇 "添加 > 容器 編排支援"。選擇 " Docker Compose",然後再次選擇 " Linux " 作為 "目标 OS"。

    In the root of the DaprBackEnd project directory, a new Dockerfile was created. The Dockerfile contains the following YAML:      在 DaprBackEnd 項目的根目錄中,建立了一個新的 Dockerfile 。 Dockerfile 包含以下 YAML:

    FROM mcr.microsoft.com/dotnet/aspnet:3.1 AS base
    WORKDIR /app
    EXPOSE 80
    EXPOSE 443
    
    FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
    WORKDIR /src
    COPY ["DaprBackEnd/DaprBackEnd.csproj", "DaprBackEnd/"]
    RUN dotnet restore "DaprBackEnd/DaprBackEnd.csproj"
    COPY . .
    WORKDIR "/src/DaprBackEnd"
    RUN dotnet build "DaprBackEnd.csproj" -c Release -o /app/build
    
    FROM build AS publish
    RUN dotnet publish "DaprBackEnd.csproj" -c Release -o /app/publish
    
    FROM base AS final
    WORKDIR /app
    COPY --from=publish /app/publish .
    ENTRYPOINT ["dotnet", "DaprBackEnd.dll"]      
    Open the docker-compose.yml file again and examine its contents. Visual Studio has updated the Docker Compose file. Now both services are included:      再次打開 docker-compose.yml docker-compose.override.yml 檔案并檢查其内容。Visual Studio 已更新 Docker Compose 檔案。現在包括兩個服務:
    version: '3.4'
    
    services:
      daprfrontend:
        image: ${DOCKER_REGISTRY-}daprfrontend
        build:
          context: .
          dockerfile: DaprFrontEnd/Dockerfile
    
      daprbackend:
        image: ${DOCKER_REGISTRY-}daprbackend
        build:
          context: .
          dockerfile: DaprBackEnd/Dockerfile       
  • To use Dapr building blocks from inside a containerized application, you'll need to add the Dapr sidecars containers to your Compose file. Carefully update the content of the docker-compose.yml file to match the following example. Pay close attention to the formatting and spacing and don't use tabs.      若要在容器化應用程式中使用 Dapr 建構塊,需要将 Dapr 邊車容器添加到Compose檔案中。仔細更新 docker-compose.yml 檔案的内容,以比對以下示例。請密切注意格式和間距,請勿使用tabs。
    version: '3.4'
    
    services:
      daprfrontend:
        image: ${DOCKER_REGISTRY-}daprfrontend
        build:
          context: .
          dockerfile: DaprFrontEnd/Dockerfile
        ports:
          - "51000:50001"
    
      daprfrontend-dapr:
        image: "daprio/daprd:latest"
        command: [ "./daprd", "-app-id", "daprfrontend", "-app-port", "443", "-app-ssl" ]
        depends_on:
          - daprfrontend
        network_mode: "service:daprfrontend"
    
      daprbackend:
        image: ${DOCKER_REGISTRY-}daprbackend
        build:
          context: .
          dockerfile: DaprBackEnd/Dockerfile
        ports:
          - "52000:50001"
    
      daprbackend-dapr:
        image: "daprio/daprd:latest"
        command: [ "./daprd", "-app-id", "daprbackend", "-app-port", "443", "-app-ssl" ]
        depends_on:
          - daprbackend
        network_mode: "service:daprbackend"      
    In the updated file, we've added daprfrontend-dapr and daprbackend-dapr sidecars for the daprfrontend and daprbackend services respectively. In the updated file, pay close attention to the following changes:      在更新的檔案中,我們分别為daprfrontend 和 daprbackend服務添加了 daprfrontend-dapr 和 daprbackend-dapr邊車。在更新的檔案中,請密切注意以下更改:
  • The sidecars use the daprio/daprd:latest container image. The use of the latest tag isn't recommended for production scenarios. For production, it's better to use a specific version number.      邊車使用 daprio/daprd:latest 容器映像。不推薦在生産方案中使用 latest 标記。對于生産環境,最好使用特定的版本号。
  • Each service defined in the Compose file has its own network namespace for network isolation purposes. The sidecars use network_mode: "service:..." to ensure they run in the same network namespace as the application. Doing so allows the sidecar and the application to communicate using localhost.      出于網絡隔離目的,Compose 檔案中定義的每個服務都有自己的網絡命名空間。邊車使用 network_mode: "service:..." 來確定它們在與應用程式相同的網絡命名空間中運作。這樣做可讓邊車和應用程式使用localhost 進行通信 。
  • The ports on which the Dapr sidecars are listening for gRPC communication (by default 50001) must be exposed to allow the sidecars to communicate with each other.      Dapr 邊車偵聽 gRPC 通信的端口 (預設為 50001) ,使邊車能夠互相通信。ports指令使用"宿主(容器所在的主機,此處為wsl)端口:容器端口 (容器内部端口)(HOST:CONTAINER) "格式,或者僅僅指定容器的端口(宿主将會随機選擇端口)都可以。
  • Run the solution (F5 or Ctrl+F5) to verify that it works as expected. If everything is configured correctly, you should see the weather forecast data:      運作解決方案 (F5 或 Ctrl+F5) 驗證其是否正常工作。如果一切配置正确,應會看到天氣預報資料:
    面向.NET開發人員的Dapr——入門

    Running locally with Docker Compose and Visual Studio 2019, you can set breakpoints and debug into the application. For production scenarios, it's recommended to host your application in Kubernetes. This book includes an accompanying reference application, eShopOnDapr, that contains scripts to deploy to Kubernetes.      使用 Docker Compose 和 Visual Studio 2019 在本地運作,可以設定斷點并在應用程式中調試。對于生産場景,建議在 Kubernetes 中托管應用程式。本書包含随附的參考應用程式 eShopOnDapr,其中包含要部署到 Kubernetes 的腳本。

    To learn more about the Dapr service invocation building block used in this walkthrough, refer to chapter 6.      若要詳細了解本演練中使用的 Dapr 服務調用建構塊,請參閱第 6 章。

Summary

總結

In this chapter, you had an opportunity to test drive Dapr. Using the Dapr .NET SDK, you saw how Dapr integrates with the .NET application platform.

在本章中,你有機會嘗試駕馭Dapr 。使用 Dapr .NET SDK,你已了解 Dapr 如何與 .NET 應用平台內建。

The first example was a simple, stateful, .NET Console application that used the Dapr state management building block.

第一個示例是使用 Dapr 狀态管理建構塊的簡單有狀态 .NET 控制台應用程式。

The second example involved a multi-container application running in Docker. By using Visual Studio with Docker Compose, you experienced the familiar F5 debugging experience available across all .NET apps.

第二個示例涉及在 Docker 中運作的多容器應用程式。通過結合使用Visual Studio 與 Docker Compose ,你可以在所有 .NET 應用中使用熟悉的 F5 調試體驗 。

You also got a closer look at Dapr component configuration files. They configure the actual infrastructure implementation used by the Dapr building blocks. You can use namespaces and scopes to restrict component access to particular environments and applications.

繼續閱讀