Community编程与开发github.com

akka-net-best-practices

关键的Akka.NET最佳实践,包括EventStream与DistributedPubSub、监督策略、错误处理、Props与依赖注入、工作分发模式以及集群/本地模式抽象,以确保可测试性。

akka-net-best-practices 是什么?

该技能文档系统性地介绍了Akka.NET开发中的核心最佳实践,涵盖通信模式选择、错误处理、工作分发和可测试性设计。它明确区分了仅限本地使用的EventStream和跨节点通信的DistributedPubSub,并提供了详细的配置示例和主题设计模式。在错误处理方面,它强调了监督策略(用于子Actor)与try-catch(用于预期失败)的适用场景,并指出了吞没未知异常的反模式。此外,文档还指导了Props与DependencyResolver的选择时机,介绍了数据库驱动队列、Akka.Streams限流等三种工作分发模式,以及通过`AkkaExecutionMode`枚举和`GenericChildPerEntityParent`等抽象实现本地测试与集群生产环境的无缝切换。该实践集成了Actor日志(ILoggingAdapter)和异步操作CancellationToken管理,适用于所有使用Akka.NET构建分布式系统的开发者。

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

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Akka.NET 最佳实践

何时使用此技能

在以下情况使用此技能:

  • 设计 Actor 通信模式
  • 在 EventStream 和 DistributedPubSub 之间做决策
  • 在 Actor 中实现错误处理
  • 理解监督策略
  • 在 Props 模式和 DependencyResolver 之间做出选择
  • 设计跨节点的工作分发
  • 创建可在有或没有集群基础设施的情况下运行的可测试 Actor 系统
  • 为本地测试场景抽象化集群分片

参考文件


1. EventStream vs DistributedPubSub

关键点:EventStream 仅限本地

Context.System.EventStream 是单个 ActorSystem 进程本地的。它不能在集群节点之间工作。

// 不好:这仅适用于单台服务器
// 当您添加第二台服务器时,第二台服务器上的订阅者将不会收到来自第一台服务器的事件
Context.System.EventStream.Subscribe(Self, typeof(PostCreated));
Context.System.EventStream.Publish(new PostCreated(postId, authorId));

何时适合使用 EventStream:

  • 单个进程内的日志记录和诊断
  • 真正的单进程应用程序的本地事件总线
  • 开发/测试场景

多节点场景使用 DistributedPubSub

对于必须跨多个集群节点到达 Actor 的事件,请使用 Akka.Cluster.Tools.PublishSubscribe:

using Akka.Cluster.Tools.PublishSubscribe;

public class TimelineUpdatePublisher : ReceiveActor
{
    private readonly IActorRef _mediator;

    public TimelineUpdatePublisher()
    {
        // 获取 DistributedPubSub 中介者
        _mediator = DistributedPubSub.Get(Context.System).Mediator;

        Receive<PublishTimelineUpdate>(msg =>
        {
            // 发布到一个主题 - 将到达所有节点上的所有订阅者
            _mediator.Tell(new Publish($"timeline:{msg.UserId}", msg.Update));
        });
    }
}

Akka.Hosting 中 DistributedPubSub 的配置

builder.WithDistributedPubSub(role: null); // 在所有角色上可用,或指定一个角色

主题设计模式

模式主题格式用例
按用户timeline:{userId}时间线更新,通知
按实体post:{postId}帖子互动更新
广播system:announcements系统范围的通知
基于角色workers:rss-poller工作分发

2. 监督策略

关键澄清:监督是针对子 Actor 的

在 Actor 上定义的监督策略决定了该 Actor 如何监督其子 Actor,而不是该 Actor 自身如何被监督。

public class ParentActor : ReceiveActor
{
    // 此策略适用于 ParentActor 的子 Actor,而非 ParentActor 本身
    protected override SupervisorStrategy SupervisorStrategy()
    {
        return new OneForOneStrategy(
            maxNrOfRetries: 10,
            withinTimeRange: TimeSpan.FromSeconds(30),
            decider: ex => ex switch
            {
                ArithmeticException => Directive.Resume,
                NullReferenceException => Directive.Restart,
                ArgumentException => Directive.Stop,
                _ => Directive.Escalate
            });
    }
}

默认监督策略

默认的 OneForOneStrategy 已经包含了速率限制:

  • 1 秒内重启 10 次 = Actor 被永久停止
  • 这防止了无限重启循环

您很少需要自定义策略,除非您有特定要求。

何时定义自定义监督

好的理由:

  • Actor 抛出指示不可恢复状态损坏的异常 -> 重启
  • Actor 抛出不应导致重启的异常(预期失败)-> 恢复
  • 子 Actor 失败应影响其兄弟 Actor -> 使用 AllForOneStrategy
  • 需要不同于默认的重试限制

坏的理由:

  • “只是为了安全” - 默认值已经足够安全
  • 不理解 Actor 的功能 - 请先理解它

3. 错误处理:监督 vs Try-Catch

何时使用 Try-Catch(大多数情况)

在以下情况使用 try-catch:

  • 失败是预期的(网络超时、无效输入、外部服务宕机)
  • 您确切知道异常发生的原因
  • 您可以优雅地处理它(重试、返回错误响应、记录日志并继续)
  • 重启没有帮助(同样的错误会再次发生)
public class RssFeedPollerActor : ReceiveActor
{
    public RssFeedPollerActor()
    {
        ReceiveAsync<PollFeed>(async msg =>
        {
            try
            {
                var feed = await _httpClient.GetStringAsync(msg.FeedUrl);
                var items = ParseFeed(feed);
                // 处理项目...
            }
            catch (HttpRequestException ex)
            {
                // 预期失败 - 记录日志并安排重试
                _log.Warning("Feed {Url} 不可用: {Error}", msg.FeedUrl, ex.Message);
                Context.System.Scheduler.ScheduleTellOnce(
                    TimeSpan.FromMinutes(5), Self, msg, Self);
            }
            catch (XmlException ex)
            {
                // 无效的 Feed 格式 - 记录日志并标记为坏
                _log.Error("Feed {Url} 格式无效: {Error}", msg.FeedUrl, ex.Message);
                Sender.Tell(new FeedPollResult.InvalidFormat(msg.FeedUrl));
            }
        });
    }
}

何时让监督来处理

让异常传播(触发监督)在以下情况:

  • 您不知道异常发生的原因
  • Actor 的状态可能已损坏
  • 重启会有帮助(重置状态、重连资源)
  • 这是编程错误(NullReferenceException、由错误逻辑导致的 InvalidOperationException)

反模式:吞没未知异常

// 不好:吞没异常会隐藏问题
catch (Exception ex)
{
    _log.Error(ex, "处理工作时发生错误");
    // Actor 以可能损坏的状态继续运行
}

// 好:处理已知异常,让未知异常传播
catch (HttpRequestException ex)
{
    // 已知的、预期的失败 - 优雅处理
    _log.Warning("HTTP 请求失败: {Error}", ex.Message);
    Sender.Tell(new WorkResult.TransientFailure());
}
// 未知异常传播到监督

4. Props vs DependencyResolver

何时使用普通 Props

在以下情况使用 Props.Create():

  • Actor 不需要 IServiceProvider 或 IRequiredActor<T>
  • 所有依赖项都可以通过构造函数传递
  • Actor 简单且自包含
// 没有 DI 需求的简单 Actor
public static Props Props(PostId postId, IPostWriteStore store)
    => Akka.Actor.Props.Create(() => new PostEngagementActor(postId, store));

何时使用 DependencyResolver

在以下情况使用 resolver.Props<T>():

  • Actor 需要 IServiceProvider 来创建作用域服务
  • Actor 使用 IRequiredActor<T> 获取对其他 Actor 的引用
  • Actor 有许多已经在 DI 容器中的依赖项
// 使用 DI 注册
builder.WithActors((system, registry, resolver) =>
{
    var actor = system.ActorOf(resolver.Props<OrderProcessorActor>(), "order-processor");
    registry.Register<OrderProcessorActor>(actor);
});

远程部署注意事项

您几乎永远不需要远程部署。 如果您不在做远程部署(并且您很可能不在做):

  • 使用闭包的 Props.Create(() => new Actor(...)) 是完全可以的
  • “序列化问题”警告不适用

对于大多数应用程序,使用集群分片而不是远程部署 - 它会自动处理分布。


5. 工作分发模式

当您有许多后台作业(RSS 源、电子邮件发送等)时,不要一次性全部处理 - 这会导致惊群问题。

解决此问题的三种模式:

  1. 数据库驱动的工作队列 - 使用 FOR UPDATE SKIP LOCKED 实现自然的跨节点分发
  2. Akka.Streams 速率限制 - 在单个节点内限制处理速度
  3. 持久化队列(发件箱模式) - 基于数据库的发件箱,用于可靠处理

有关完整的代码示例,请参见 work-distribution-patterns.md。


6. 常见错误总结

错误为什么是错的修复
使用 EventStream 进行跨节点发布/订阅EventStream 仅限本地使用 DistributedPubSub
定义监督来“保护”一个 Actor监督保护的是子 Actor理解层次结构
捕获所有异常隐藏错误,损坏状态仅捕获预期的错误
总是使用 DependencyResolver增加不必要的复杂性尽可能使用普通 Props
一次性处理所有后台作业惊群效应,资源耗尽使用数据库队列 + 速率限制
为预期失败抛出异常触发不必要的重启返回结果类型,使用消息传递

7. 快速参考

通信模式决策树

需要在 Actor 之间通信?
├── 仅同一进程? -> 可以使用 EventStream
├── 跨集群节点?
│   ├── 点对点? -> 使用 ActorSelection 或已知的 IActorRef
│   └── 发布/订阅? -> 使用 DistributedPubSub
└── 向外部系统发送即发即弃消息? -> 考虑发件箱模式

错误处理决策树

Actor 中发生异常?
├── 预期失败(HTTP 超时、无效输入)?
│   └── Try-catch,优雅处理,继续
├── 状态可能已损坏?
│   └── 让监督重启
├── 原因未知?
│   └── 让监督重启
└── 编程错误(null 引用、错误逻辑)?
    └── 让监督重启,修复错误

Props 决策树

创建 Actor Props?
├── Actor 需要 IServiceProvider?
│   └── 使用 resolver.Props<T>()
├── Actor 需要 IRequiredActor<T>?
│   └── 使用 resolver.Props<T>()
├── 带有构造函数参数的简单 Actor?
│   └── 使用 Props.Create(() => new Actor(...))
└── 需要远程部署?
    └── 可能不需要 - 请改用集群分片

8. 集群/本地模式抽象

对于需要在集群生产环境和本地/测试环境中运行的应用程序,使用抽象模式在实现之间切换:

  • AkkaExecutionMode 枚举 - 控制使用哪些实现(LocalTest vs Clustered)
  • GenericChildPerEntityParent - 使用相同的 IMessageExtractor 在本地模拟分片行为
  • IPubSubMediator - 抽象化 DistributedPubSub,以实现可切换的本地/集群实现

有关完整的实现代码,请参见 cluster-local-abstractions.md。


9. Actor 日志记录

使用 ILoggingAdapter,而非 ILogger

在 Actor 中,使用来自 Context.GetLogger() 的 ILoggingAdapter,而不是通过 DI 注入的 ILogger<T>:

public class MyActor : ReceiveActor
{
    private readonly ILoggingAdapter _log = Context.GetLogger();

    public MyActor()
    {
        Receive<MyMessage>(msg =>
        {
            _log.Info("正在为用户 {UserId} 处理消息", msg.UserId);
            _log.Error(ex, "处理 {MessageType} 失败", msg.GetType().Name);
        });
    }
}

为什么使用 ILoggingAdapter:

  • 与 Akka 的日志记录管道和监督集成
  • 从 v1.5.57 起支持语义化/结构化日志记录
  • 方法名称:Info()、Debug()、Warning()、Error()(不是 Log* 变体)
  • 不需要 DI - 直接从 Actor 上下文获取

不要将 ILogger 注入 Actor - 它会绕过 Akka 的日志记录基础设施。

语义化日志记录(v1.5.57+)

// 命名占位符,以实现更好的日志聚合和查询
_log.Info("订单 {OrderId} 已为客户 {CustomerId} 处理", order.Id, order.CustomerId);

// 优先使用命名占位符而不是位置占位符
// 好:{OrderId}, {CustomerId}
// 避免:{0}, {1}

10. 使用 CancellationToken 管理异步操作

当 Actor 通过 PipeTo 启动异步操作时,如果管理不当,这些操作可能比 Actor 存活得更久。关键实践:

  • 在 PostStop 中处理 Actor CTS - 始终在 PostStop() 中取消并释放
  • 每个操作使用新的 CTS - 在开始新工作之前取消上一个
  • 到处传递 Token - EF Core 查询、HTTP 调用等
  • 为超时链接 CTS - 外部调用应设置较短超时,以防止挂起
  • 优雅处理 - 在 catch 块中区分超时和关闭

有关完整的实现代码,请参见 async-cancellation-patterns.md。

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-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

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.

相关技能