Community程式設計與開發github.com

akka-net-management

Akka.Management 用於叢集啟動、服務發現(Kubernetes、Azure、Config)、健康檢查以及無需靜態種子節點的動態叢集形成。

akka-net-management 是什麼?

此技能提供 Akka.Management 與 Akka.Cluster.Bootstrap 的整合指南,讓開發者能動態形成 Akka.NET 叢集,取代傳統的靜態種子節點方式。它支援多種服務發現提供者,包括 Kubernetes API、Azure Table Storage 以及基於 HOCON 組態的靜態發現,適用於雲端與容器化環境。技能內容涵蓋所需的 NuGet 套件、使用 Akka.Hosting 進行組態設定的 C# 程式碼範例,以及如何設定健康檢查端點(如 `/alive` 與 `/ready`)來整合負載平衡器與編排器。此外,文件中提供完整的疑難排解指南,協助處理叢集無法形成、腦裂問題以及 Azure 發現失敗等常見狀況,並包含 Aspire 整合範例,適合需要動態擴展與高可用性的生產環境部署。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/akka-management

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Akka.NET 管理與服務發現

何時使用此技能

使用此技能的情況:

  • 將 Akka.NET 叢集部署到 Kubernetes 或雲端環境
  • 用動態服務發現取代靜態種子節點
  • 設定叢集啟動以實現自動形成
  • 為負載平衡器設定健康端點
  • 與 Azure Table Storage、Kubernetes API 或基於組態的發現整合

參考文件

概述

Akka.Management 提供 HTTP 端點進行叢集管理,並與 Akka.Cluster.Bootstrap 整合,能透過服務發現取代靜態種子節點,實現動態叢集形成。

為什麼使用 Akka.Management?

方式優點缺點
靜態種子節點簡單、無相依性無法擴展、需要已知 IP
Akka.Management動態發現、可擴展至 N 個節點較多組態、外部相依性

使用靜態種子節點的時機:開發環境、單節點部署、固定基礎設施。

使用 Akka.Management 的時機:Kubernetes、自動擴展群組、動態環境、生產叢集。


架構

┌─────────────────────────────────────────────────────────────┐
│                     叢集啟動                                 │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐     │
│  │  節點 1     │    │  節點 2     │    │  節點 3     │     │
│  │             │    │             │    │             │     │
│  │ Management  │◄──►│ Management  │◄──►│ Management  │     │
│  │ HTTP :8558  │    │ HTTP :8558  │    │ HTTP :8558  │     │
│  └──────┬──────┘    └──────┬──────┘    └──────┬──────┘     │
│         │                  │                  │             │
│         └──────────────────┼──────────────────┘             │
│                            │                                │
│                    ┌───────▼───────┐                        │
│                    │   發現提供者   │                        │
│                    └───────────────┘                        │
│                            │                                │
└────────────────────────────┼────────────────────────────────┘
                             │
              ┌──────────────┼──────────────┐
              │              │              │
        ┌─────▼─────┐ ┌──────▼─────┐ ┌─────▼──────┐
        │ Kubernetes│ │   Azure    │ │   Config   │
        │    API    │ │   Tables   │ │   (HOCON)  │
        └───────────┘ └────────────┘ └────────────┘

所需的 NuGet 套件

<ItemGroup>
  <!-- 核心管理 -->
  <PackageReference Include="Akka.Management" />
  <PackageReference Include="Akka.Management.Cluster.Bootstrap" />

  <!-- 選擇一個發現提供者 -->
  <PackageReference Include="Akka.Discovery.KubernetesApi" />    <!-- 用於 Kubernetes -->
  <PackageReference Include="Akka.Discovery.Azure" />            <!-- 用於 Azure -->
  <PackageReference Include="Akka.Discovery.Config.Hosting" />   <!-- 用於靜態組態 -->
</ItemGroup>

Akka.Hosting 組態設定

基本設定與模式選擇

public static class AkkaConfiguration
{
    public static IServiceCollection ConfigureAkka(
        this IServiceCollection services,
        Action<AkkaConfigurationBuilder, IServiceProvider>? additionalConfig = null)
    {
        services.AddOptions<AkkaSettings>()
            .BindConfiguration("AkkaSettings")
            .ValidateDataAnnotations()
            .ValidateOnStart();

        return services.AddAkka("MySystem", (builder, sp) =>
        {
            var settings = sp.GetRequiredService<IOptions<AkkaSettings>>().Value;
            var configuration = sp.GetRequiredService<IConfiguration>();

            ConfigureNetwork(builder, settings, configuration);
            ConfigureHealthChecks(builder);

            additionalConfig?.Invoke(builder, sp);
        });
    }

    private static void ConfigureNetwork(
        AkkaConfigurationBuilder builder,
        AkkaSettings settings,
        IConfiguration configuration)
    {
        if (settings.ExecutionMode == AkkaExecutionMode.LocalTest)
            return;

        builder.WithRemoting(settings.RemoteOptions);

        if (settings.ClusterBootstrapOptions.Enabled)
            ConfigureAkkaManagement(builder, settings, configuration);
        else
            builder.WithClustering(settings.ClusterOptions);
    }
}

Akka.Management 組態設定

private static void ConfigureAkkaManagement(
    AkkaConfigurationBuilder builder,
    AkkaSettings settings,
    IConfiguration configuration)
{
    var mgmtOptions = settings.AkkaManagementOptions;
    var bootstrapOptions = settings.ClusterBootstrapOptions;

    // 重要:使用 Akka.Management 時清除種子節點
    settings.ClusterOptions.SeedNodes = [];

    builder
        .WithClustering(settings.ClusterOptions)
        .WithAkkaManagement(setup =>
        {
            setup.Http.HostName = mgmtOptions.HostName;
            setup.Http.Port = mgmtOptions.Port;
            setup.Http.BindHostName = "0.0.0.0";
            setup.Http.BindPort = mgmtOptions.Port;
        })
        .WithClusterBootstrap(options =>
        {
            options.ContactPointDiscovery.ServiceName = bootstrapOptions.ServiceName;
            options.ContactPointDiscovery.PortName = bootstrapOptions.PortName;
            options.ContactPointDiscovery.RequiredContactPointsNr = bootstrapOptions.RequiredContactPointsNr;
            options.ContactPointDiscovery.Interval = bootstrapOptions.ContactPointProbingInterval;
            options.ContactPointDiscovery.StableMargin = bootstrapOptions.StableMargin;
            options.ContactPointDiscovery.ContactWithAllContactPoints = bootstrapOptions.ContactWithAllContactPoints;
            options.ContactPoint.FilterOnFallbackPort = bootstrapOptions.FilterOnFallbackPort;
            options.ContactPoint.ProbeInterval = bootstrapOptions.BootstrapperDiscoveryPingInterval;
        });

    // 設定發現提供者
    ConfigureDiscovery(builder, settings, configuration);
}

請參閱 discovery-providers.md 以取得完整的 Config、Kubernetes 及 Azure 發現設定程式碼。

請參閱 configuration-reference.md 以取得完整的強型別組態模型類別。


健康端點

Akka.Management 為負載平衡器和編排器提供健康端點:

端點用途返回 200 的條件
/alive存活ActorSystem 正在執行
/ready就緒叢集成員狀態為 Up
/cluster/members除錯傳回叢集成員資訊

ASP.NET Core 健康檢查整合

// 註冊 Akka 健康檢查
builder.Services.AddHealthChecks();

// 在 Akka 組態中
builder
    .WithActorSystemLivenessCheck()     // 新增 "akka-liveness" 健康檢查
    .WithAkkaClusterReadinessCheck();   // 新增 "akka-cluster-readiness" 健康檢查

// 對應端點
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("liveness")
});

app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("readiness")
});

疑難排解

叢集無法形成

症狀: 節點維持為獨立的單節點叢集。

檢查清單:

  1. 所有節點使用相同的 ServiceName
  2. RequiredContactPointsNr 符合實際的副本數量
  3. 發現提供者已正確設定
  4. 網路允許管理連接埠(8558)的流量
  5. 對於 Kubernetes:RBAC 權限已設定

腦裂

症狀: 形成多個叢集而非單一叢集。

解決方案:

  1. 設定 ContactWithAllContactPoints = true
  2. 在較慢的環境中增加 StableMargin
  3. 對於 Aspire:設定 FilterOnFallbackPort = false(動態連接埠)
  4. 對於 Kubernetes:設定 FilterOnFallbackPort = true(固定連接埠)

Azure 發現問題

症狀: 節點無法透過 Azure Tables 找到彼此。

檢查清單:

  1. 連接字串有效
  2. 儲存體帳戶允許資料表操作
  3. 所有節點使用相同的 ServiceName
  4. 防火牆允許存取 Azure Storage

Aspire 整合

如需詳細的 Aspire 特定模式,請參閱 akka-net-aspire-configuration 技能。

Aspire 快速參考:

// 在 AppHost 中
appBuilder
    .WithEndpoint(name: "remote", protocol: ProtocolType.Tcp,
        env: "AkkaSettings__RemoteOptions__Port")
    .WithEndpoint(name: "management", protocol: ProtocolType.Tcp,
        env: "AkkaSettings__AkkaManagementOptions__Port")
    .WithEnvironment("AkkaSettings__ClusterBootstrapOptions__Enabled", "true")
    .WithEnvironment("AkkaSettings__ClusterBootstrapOptions__DiscoveryMethod", "AzureTableStorage")
    .WithEnvironment("AkkaSettings__ClusterBootstrapOptions__FilterOnFallbackPort", "false");

總結:何時使用哪種方法

情境發現方法FilterOnFallbackPort
本機開發(單一節點)無(使用種子節點)不適用
Aspire 多節點AzureTableStoragefalse
KubernetesKubernetestrue
Azure VM/VMSSAzureTableStoragetrue
固定基礎設施Configtrue
AWS ECS/EC2AWS 發現外掛程式true

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

marketplace-publishing

Workflow for publishing skills and agents to the dotnet-skills Claude Code marketplace. Covers adding new content, updating plugin.json, validation, and release tagging.

相關技能