Community编程与开发github.com

Akka.NET 管理与服务发现

Akka.Management 用于集群引导、服务发现(Kubernetes、Azure、配置)、健康检查以及无需静态种子节点的动态集群组建。

Akka.NET 管理与服务发现 是什么?

该技能详细介绍了如何利用 Akka.Management 和 Akka.Cluster.Bootstrap 在 Akka.NET 集群中实现动态服务发现和自动集群组建,从而替代传统的静态种子节点方式。它支持通过 Kubernetes API、Azure 表存储或 HOCON 配置等多种发现提供者,使集群能够自动适应节点变化,非常适合云环境(如 Kubernetes、Azure VMs 或 AWS ECS)。除了核心配置,该技能还涵盖了健康检查端点(/alive、/ready)以及与 ASP.NET Core 健康检查的集成,帮助开发者为负载均衡器和编排器提供准确的节点状态信息。此外,它还提供了针对集群无法组建、脑裂问题以及 Azure 发现故障的详细排查指南,并特别介绍了与 .NET 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 表存储、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    │ │   配置     │
        │    API    │ │   表       │ │   (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 获取完整的配置、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 表相互发现。

检查清单:

  1. 连接字符串有效
  2. 存储帐户允许表操作
  3. 所有节点使用相同的 ServiceName
  4. 防火墙允许访问 Azure 存储

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
本地开发(单节点)无(使用种子节点)N/A
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.

相关技能