面向.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 的基本概念?,F在實操一下。本章將指導你完成本地開發環境的準備工作,并構建兩個 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.
Install the Dapr CLI. It enables you to launch, run, and manage Dapr instances. It also provides debugging support.
Install?Docker Desktop. If you're running on Windows, make sure that?Docker Desktop for Windows?is configured to use Linux containers.
首先,在開發計算機上安裝 Dapr。完成后,可以在?自承載模式下構建并運行 Dapr 應用程序。
安裝 DAPR CLI。它使您可以啟動、運行和管理 Dapr 實例。它還提供調試支持。
安裝?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 容器。
Initialize Dapr. This step sets up your development environment by installing the latest Dapr binaries and container images.
Install the?.NET Core 3.1 SDK.
初始化 Dapr。此步驟通過安裝最新的 Dapr 二進制文件和容器映像來設置開發環境。
安裝?.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
創建應用程序
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 DaprCounterThe command scaffolds a simple "Hello World" .NET Core application. ?? ??該命令搭建簡單的"Hello World“.NET Core 應用程序。
Then, navigate into the new directory created by the previous command:? ? ??然后,定位到上一命令創建的新目錄:
cd DaprCounterRun the newly created application using the?dotnet run?command. Doing so writes "Hello World!" to the console screen:? ? ??使用?dotnet run?命令運行新創建的應用程序。這樣做會在控制臺屏幕上輸出"Hello World!"?:
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 緊密集成。
From the terminal window, add the?Dapr.Client?NuGet package to your application:? ? ??在終端窗口中,將?Dapr.Client?的NuGet 包添加到應用程序:
dotnet add package Dapr.ClientNote
If you're working with a pre-release version of Dapr, be sure to add the?--prerelease?flag to the command.
備注
如果使用 Dapr 的預發行版本,請確保在命令中添加?--prerelease?標志。
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 構建塊會使應用程序具有狀態。 - Important - 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.redisversion: v1metadata:- name: redisHostvalue: localhost:6379- name: redisPasswordvalue: ""- name: actorStateStorevalue: "true"- Note - 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?p. 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: statestorenamespace: production spec:type: state.redisversion: v1metadata:- name: redisHostvalue: localhost:6379- name: redisPasswordvalue: ""- name: actorStateStorevalue: "true"- Important - 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: statestorenamespace: production spec:type: state.redisversion: v1metadata:- name: redisHostvalue: localhost:6379- name: redisPasswordvalue: ""- name: actorStateStorevalue: "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中完成此示例。 - Create the application- 創建應用程序
- In Visual Studio 2019, create an ASP.NET Core Web App project:? ? ??在 Visual Studio 2019 中,創建ASP.NET Core Web 應用項目?: 
- Name your project?DaprFrontEnd?and your solution?DaprMultiContainer:? ? ? 項目命名為?DaprFrontEnd?,解決方案命名為?DaprMultiContainer?: 
- 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 支持。 
- 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 配置"復選框。 
- 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- Note - If you're targeting a version of?Dapr.AspNetCore?that is in prerelease, you need to specify the?-Prerelease?flag. - 備注 - 如果要以?Dapr.AspNetCore?的預發行版本為目標,則需要指定?-Prerelease?標志。 
- 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邊車、構建塊和組件通信。 
- 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; }} }?
- 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中。 
- 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>
- Right-click the?DaprFrontEnd?project, and choose?Add?>?Container Orchestrator Support. The?Add Container Orchestrator Support?dialog appears:? ? ??右擊?DaprFrontEnd?項目,然后選擇 "添加?>?容器編排支持"。將顯示?"添加容器編排支持?"對話框: - Choose Docker Compose. ?? ??選擇“Docker Compose”。 
- In the next dialog, select Linux as the Target OS:? ? ??下一個對話框中,選擇?"Linux"?作為"目標 OS": - 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?文件: - 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-}daprfrontendbuild: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 443FROM 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/buildFROM build AS publish RUN dotnet publish "DaprFrontEnd.csproj" -c Release -o /app/publishFROM 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。 
- Pulls the?mcr.microsoft.com/dotnet/aspnet:3.1?image and names it?base.? ? ??拉取?mcr.microsoft.com/dotnet/aspnet:3.1?鏡像,將其命名為?base?。 
- Sets the working directory to?/app.? ? ??將工作目錄設置為?/app。WORKDIR指令指定后續指令的工作目錄 
- Exposes port?80?and?443.? ? ? 聲明窗口要公開?80?端口和?443端口,這些端口都是容器內部端口,非宿主端口?。 
- Pulls the?mcr.microsoft.com/dotnet/sdk:3.1?image and names it?build.? ? ??拉取?mcr.microsoft.com/dotnet/sdk:3.1?鏡像,將其命名為?build?。 
- Sets the working directory to?/src.? ? ??將工作目錄設置為?/src。 
- Copies the?DaprFrontEnd/DaprFrontEnd.csproj?to a new directory named?DaprFrontEnd/.? ? ??將?DaprFrontEnd/DaprFrontEnd.csproj?復制到名為?DaprFrontEnd/ 的新目錄。COPY指令將Dockerfile所在目錄中的文件拷貝到鏡像中 
- Calls?dotnet restore?on the project.? ? ??對項目調用?dotnet restore? 。 
- Copies everything from the root directory into the image's root. ?? ??將根目錄中的所有內容復制到鏡像的根目錄中。 
- Sets the working directory to?/src/DaprFrontEnd.? ? ??將工作目錄設置為?/src/DaprFrontEnd。 
- Calls?dotnet build?on the project.? ? ??對該項目調用?dotnet build? 
- Initializes a new build stage from the existing?build?base image and names it?publish.? ? ??從現有build鏡像初始化新的構建階段并命名為?publish?。 
- Calls?dotnet publish?on the project.? ? ??對項目調用?dotnet publish。 
- Initializes a new build stage from the existing?publish?base image and names it?final.? ? ??從現有base鏡像初始化新的構建階段并命名為?final?。 
- Sets the working directory to?/app.? ? ??將工作目錄設置為?/app。 
- Copies the?/app/publish?directory from the?publish?image into the root of the?final?image.? ? ?從publish?鏡像將?/app/publish?目錄復制到final鏡像的根目錄?。 
- 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 443FROM 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/buildFROM build AS publish RUN dotnet publish "DaprBackEnd.csproj" -c Release -o /app/publishFROM 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-}daprfrontendbuild:context: .dockerfile: DaprFrontEnd/Dockerfiledaprbackend:image: ${DOCKER_REGISTRY-}daprbackendbuild: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-}daprfrontendbuild:context: .dockerfile: DaprFrontEnd/Dockerfileports:- "51000:50001"daprfrontend-dapr:image: "daprio/daprd:latest"command: [ "./daprd", "-app-id", "daprfrontend", "-app-port", "443", "-app-ssl" ]depends_on:- daprfrontendnetwork_mode: "service:daprfrontend"daprbackend:image: ${DOCKER_REGISTRY-}daprbackendbuild:context: .dockerfile: DaprBackEnd/Dockerfileports:- "52000:50001"daprbackend-dapr:image: "daprio/daprd:latest"command: [ "./daprd", "-app-id", "daprbackend", "-app-port", "443", "-app-ssl" ]depends_on:- daprbackendnetwork_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) 驗證其是否正常工作。如果一切配置正確,應會看到天氣預報數據: - 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. - 你還可以更深入地了解 Dapr 組件配置文件。它們配置 Dapr 構建塊使用的實際基礎設施實現。你可以使用命名空間和范圍限制特定環境和應用程序對組件的訪問。 - In the upcoming chapters, you'll dive deep into the building blocks offered by Dapr. - 在即將推出的章節中,你將深入了解 Dapr 提供的構建塊。 - 目錄:- 面向.NET開發人員的Dapr——前言
- 面向.NET開發人員的Dapr——分布式世界
- 面向.NET開發人員的Dapr——俯瞰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。
Add container support
添加容器支持
In the final part of this example, you'll add container support and run the solution using Docker Compose.
最后,你將添加容器支持,并使用 Docker Compose 運行解決方案。
總結
以上是生活随笔為你收集整理的面向.NET开发人员的Dapr——入门的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: C# 三种方式实现Socket数据接收(
- 下一篇: 【12图】你管这破玩意叫Pulsar
