Community程式設計與開發github.com

akk-net-best-practices

關鍵的 Akka.NET 最佳實務,包括 EventStream 與 DistributedPubSub、監督策略、錯誤處理、Props 與 DependencyResolver、工作分配模式以及促進可測試性的叢集/本機模式抽象。

akk-net-best-practices 是什麼?

這個 Akka.NET 技能提供了開發人員建置高品質、可測試且具備叢集感知能力的 Akka.NET 應用程式的關鍵最佳實務指南。它詳細比較了 EventStream (僅限本機) 與 DistributedPubSub (跨節點) 的用途,強調在錯誤處理中應優先使用 try-catch 處理預期錯誤,並讓監督策略處理未知的或會導致狀態損毀的例外狀況。技能也釐清了在簡單案例中使用 Props.Create() 與在需要依賴注入 (IServiceProvider) 時使用 DependencyResolver 的選擇時機,同時指出遠端部署通常是不必要的,應優先考慮叢集分片。此外,它還說明了使用資料庫佇列與 Akka.Streams 速率限制來解決大量背景工作因「驚群效應」導致資源耗盡的工作分配模式,並提供了用於本機測試的叢集/本機模式抽象 (如 `GenericChildPerEntityParent` 和 `IPubSubMediator`),讓應用程式能在不啟動完整叢集的情況下進行測試。此技能適用於 Claude Code、Cursor 和 Codex 等 AI 代理平台,並以 SKILL.md 的形式提供詳細的參考檔案,涵蓋工作分配、叢集/本機抽象以及非同步取消模式。

相容平台~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 系統
  • 為本機測試情境建立 Cluster Sharding 的抽象層

參考文件


1. EventStream 與 DistributedPubSub

關鍵:EventStream 僅限本機

Context.System.EventStream 僅限於單一 ActorSystem 行程。它無法跨叢集節點運作。

// 錯誤:這只能在單一伺服器上運作
// 當您加入第二台伺服器時,伺服器 2 上的訂閱者將無法收到伺服器 1 發送的事件
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,而不是它自己被如何監督。

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 擲出的例外表示狀態已不可恢復地損毀 -> Restart
  • Actor 擲出的例外不應觸發重新啟動(預期的失敗) -> Resume
  • 子 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 與 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. 持久化佇列(輸出箱模式) - 基於資料庫的輸出箱,用於可靠處理

請參閱 工作分配模式.md 以取得完整的程式碼範例。


6. 常見錯誤總結

錯誤為什麼是錯的修正
使用 EventStream 進行跨節點發布/訂閱EventStream 僅限本機使用 DistributedPubSub
定義監督策略來「保護」Actor監督保護的是子 Actor了解階層結構
捕捉所有例外隱藏錯誤、損毀狀態僅捕捉預期錯誤
一律使用 DependencyResolver增加不必要的複雜度在可能的情況下使用純 Props
一次處理所有背景工作驚群效應、資源耗盡使用資料庫佇列 + 速率限制
對預期失敗擲出例外觸發不必要的重新啟動回傳結果類型,使用訊息傳遞

7. 快速參考

通訊模式決策樹

需要在 Actor 之間通訊?
├── 僅限同一行程? -> 使用 EventStream 即可
├── 跨叢集節點?
│   ├── 點對點? -> 使用 ActorSelection 或已知的 IActorRef
│   └── 發布/訂閱? -> 使用 DistributedPubSub
└── 發送後忘記到外部系統? -> 考慮使用輸出箱模式

錯誤處理決策樹

Actor 中發生例外?
├── 可預期的失敗(HTTP 逾時、無效輸入)?
│   └── 使用 try-catch,優雅處理,繼續執行
├── 狀態可能已損毀?
│   └── 讓監督重新啟動
├── 未知原因?
│   └── 讓監督重新啟動
└── 程式設計錯誤(空引用、錯誤邏輯)?
    └── 讓監督重新啟動,修正錯誤

Props 決策樹

建立 Actor Props?
├── Actor 需要 IServiceProvider?
│   └── 使用 resolver.Props<T>()
├── Actor 需要 IRequiredActor<T>?
│   └── 使用 resolver.Props<T>()
├── 具有建構函式參數的簡單 Actor?
│   └── 使用 Props.Create(() => new Actor(...))
└── 需要遠端部署?
    └── 可能不需要 - 請改用叢集分片

8. 叢集/本機模式抽象

對於需要在叢集生產環境以及本機/測試環境中執行的應用程式,請使用抽象模式來切換實作:

  • AkkaExecutionMode 列舉 - 控制要使用哪種實作(LocalTest 與 Clustered)
  • GenericChildPerEntityParent - 使用相同的 IMessageExtractor 在本機模擬分片行為
  • IPubSubMediator - 將 DistributedPubSub 抽象化,以便在本機和叢集實作之間切換

請參閱 叢集本機抽象.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<T> 注入到 Actor 中 - 它會繞過 Akka 的記錄基礎架構。

語意式記錄 (v1.5.57+)

// 使用具名佔位符以獲得更好的記錄彙總與查詢
_log.Info("已為客戶 {CustomerId} 處理訂單 {OrderId}", order.Id, order.CustomerId);

// 優先使用具名佔位符而非位置參數
// 好:{OrderId}、{CustomerId}
// 避免:{0}、{1}

10. 使用 CancellationToken 管理非同步操作

當 Actor 透過 PipeTo 啟動非同步操作時,如果管理不當,這些操作可能會比 Actor 壽命更長。關鍵實務:

  • 在 PostStop 中處理 Actor 層級的 CTS - 務必在 PostStop() 中取消並釋放
  • 每個操作使用新的 CTS - 在開始新工作前取消前一個
  • 到處傳遞 Token - EF Core 查詢、HTTP 呼叫等
  • 使用連結的 CTS 處理逾時 - 外部呼叫應有短逾時以防止掛起
  • 優雅處理 - 在 catch 區塊中區分逾時與關機

請參閱 非同步取消模式.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.

相關技能