使用 .NET Aspire 配置 Akka.NET
何時使用此技能
在以下情況使用此技能:
- 使用 .NET Aspire 協調建立新的 Akka.NET 專案
- 配置具有叢引導和服務發現的 Akka.Cluster
- 整合 SQL Server 的 Akka.Persistence
- 設定 Akka.Management 以進行叢集管理
- 在本地開發中配置多副本 Actor 系統
- 使用 Aspire 將 Akka.NET 應用程式部署到 Kubernetes
相關技能
akka-net-management- 深入探討 Akka.Management、叢集引導以及發現提供者(Kubernetes、Azure、Config)microsoft-extensions-configuration- 用於配置驗證的 IValidateOptions 模式akka-net-best-practices- 用於可測試 Actor 系統的叢集/本地模式抽象aspire-integration-testing- 使用真實基礎設施測試 Aspire 應用程式
核心原則
- 透過 Microsoft.Extensions.Configuration 進行配置 - 使用從 appsettings.json 繫結的強型別設定類別(請參閱
microsoft-extensions-configuration技能) - 使用 Akka.Hosting 進行 DI 整合 - 使用 Akka.Hosting 程式庫實現與 ASP.NET Core 的無縫整合
- 使用 Aspire 進行協調 - 讓 Aspire 管理服務依賴項、網路和環境配置
- 健康檢查 - 始終為叢集、持久化以及就緒狀態配置健康檢查
- 關注點分離 - 將 Actor 定義、配置和 Aspire 協調保持在獨立的層次中
- 在啟動時驗證配置 - 使用
IValidateOptions<T>和.ValidateOnStart()來在配置錯誤時快速失敗
專案結構
YourSolution/
├── src/
│ ├── YourApp.Actors/ # Actor 定義與業務邏輯
│ │ ├── YourActor.cs
│ │ └── YourApp.Actors.csproj
│ ├── YourApp/ # ASP.NET Core Web 應用程式
│ │ ├── Config/
│ │ │ ├── AkkaConfiguration.cs # Akka 設定擴充方法
│ │ │ └── AkkaSettings.cs # 配置模型
│ │ ├── Program.cs
│ │ ├── appsettings.json
│ │ └── YourApp.csproj
│ └── YourApp.AppHost/ # Aspire 協調
│ ├── Program.cs
│ ├── AkkaManagementExtensions.cs
│ └── YourApp.AppHost.csproj
必要的 NuGet 套件
用於 Actor 專案 (YourApp.Actors.csproj)
<ItemGroup>
<PackageReference Include="Akka.Cluster.Hosting" />
<PackageReference Include="Akka.Streams" />
</ItemGroup>
用於 Web 應用程式 (YourApp.csproj)
<ItemGroup>
<PackageReference Include="Akka.Hosting" />
<PackageReference Include="Akka.Cluster.Hosting" />
<PackageReference Include="Akka.Persistence.Sql.Hosting" />
<PackageReference Include="Akka.Management" />
<PackageReference Include="Akka.Management.Cluster.Bootstrap" />
<PackageReference Include="Akka.Discovery.KubernetesApi" />
<PackageReference Include="Akka.Discovery.Azure" />
<PackageReference Include="Akka.Discovery.Config.Hosting" />
<PackageReference Include="Petabridge.Cmd.Host" />
<PackageReference Include="Petabridge.Cmd.Cluster" />
</ItemGroup>
用於 AppHost (YourApp.AppHost.csproj)
<Sdk Name="Aspire.AppHost.Sdk" Version="$(AspireVersion)" />
<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" />
<PackageReference Include="Aspire.Hosting.Azure.Storage" />
<PackageReference Include="Aspire.Hosting.SqlServer" />
</ItemGroup>
配置模型 (AkkaSettings.cs)
建立一個強型別的配置類別:
using System.Net;
using System.Security.Cryptography.X509Certificates;
using Akka.Cluster.Hosting;
using Akka.Remote.Hosting;
using Petabridge.Cmd.Host;
namespace YourApp.Config;
public class AkkaSettings
{
public string ActorSystemName { get; set; } = "YourSystem";
public bool LogConfigOnStart { get; set; } = false;
public RemoteOptions RemoteOptions { get; set; } = new()
{
PublicHostName = Dns.GetHostName(),
HostName = "0.0.0.0",
Port = 8081
};
public ClusterOptions ClusterOptions { get; set; } = new()
{
SeedNodes = [$