Akka.Hosting 參與者模式
何時使用此技能
在以下情況使用此技能:
- 建構代表領域物件(使用者、訂單、發票等)的實體參與者
- 需要參與者同時在單元測試(無叢集)和生產環境(叢集分片)中運作
- 使用 akka-reminders 設定排程任務
- 使用 Akka.Hosting 擴充方法註冊參與者
- 建立可重複使用的參與者設定模式
核心原則
- 執行模式抽象化 - 相同的參與者程式碼可在本機(測試)或叢集(生產)執行
- 用於本機的 GenericChildPerEntityParent - 在沒有叢集開銷的情況下模擬分片語意
- 用於路由的訊息提取器 - 重複使用 Akka.Cluster.Sharding 的 IMessageExtractor 介面
- Akka.Hosting 擴充方法 - 流暢的設定,具有良好的組合性
- 用於可測試性的 ITimeProvider - 使用 ActorSystem.Scheduler 代替 DateTime.Now
執行模式
定義一個列舉來控制參與者行為:
/// <summary>
/// 決定如何設定 Akka.NET
/// </summary>
public enum AkkaExecutionMode
{
/// <summary>
/// 純本機參與者系統 - 無遠端、無叢集。
/// 使用 GenericChildPerEntityParent 代替 ShardRegion。
/// 適用於單元測試和簡單場景。
/// </summary>
LocalTest,
/// <summary>
/// 完整的 ShardRegion 叢集。
/// 用於整合測試和生產環境。
/// </summary>
Clustered
}
GenericChildPerEntityParent
一個輕量級父參與者,將訊息路由到子實體,模擬叢集分片語意而不需要叢集:
using Akka.Actor;
using Akka.Cluster.Sharding;
/// <summary>
/// 一個通用的「每個實體一個子參與者」父參與者。
/// </summary>
/// <remarks>
/// 重複使用 Akka.Cluster.Sharding 的 IMessageExtractor 以實現一致的路由。
/// 非常適合不需要叢集開銷的單元測試。
/// </remarks>
public sealed class GenericChildPerEntityParent : ReceiveActor
{
public static Props CreateProps(
IMessageExtractor extractor,
Func<string, Props> propsFactory)
{
return Props.Create(() =>
new GenericChildPerEntityParent(extractor, propsFactory));
}
private readonly IMessageExtractor _extractor;
private readonly Func<string, Props> _propsFactory;
public GenericChildPerEntityParent(
IMessageExtractor extractor,
Func<string, Props> propsFactory)
{
_extractor = extractor;
_propsFactory = propsFactory;
ReceiveAny(message =>
{
var entityId = _extractor.EntityId(message);
if (entityId is null) return;
// 取得現有子參與者或建立新的
Context.Child(entityId)
.GetOrElse(() => Context.ActorOf(_propsFactory(entityId), entityId))
.Forward(_extractor.EntityMessage(message));
});
}
}
訊息提取器
建立實作 IMessageExtractor(來自 Akka.Cluster.Sharding)的提取器:
using Akka.Cluster.Sharding;
/// <summary>
/// 根據強型別 ID 將訊息路由到實體參與者。
/// </summary>
public sealed class OrderMessageExtractor : HashCodeMessageExtractor
{
public const int DefaultShardCount = 40;
public OrderMessageExtractor(int maxNumberOfShards = DefaultShardCount)
: base(maxNumberOfShards)
{
}
public override string? EntityId(object message)
{
return message switch
{
IWithOrderId msg => msg.OrderId.Value.ToString(),
_ => null
};
}
}
// 定義一個針對特定實體的訊息介面
public interface IWithOrderId
{
OrderId OrderId { get; }
}
// 使用強型別 ID
public readonly record struct OrderId(Guid Value)
{
public static OrderId New() => new(Guid.NewGuid());
public override string ToString() => Value.ToString();
}
Akka.Hosting 擴充方法
建立抽象化執行模式的擴充方法:
using Akka.Cluster.Hosting;
using Akka.Cluster.Sharding;
using Akka.Hosting;
public static class OrderActorHostingExtensions
{
/// <summary>
/// 新增 OrderActor,支援本機和叢集模式。
/// </summary>
public static AkkaConfigurationBuilder WithOrderActor(
this AkkaConfigurationBuilder builder,
AkkaExecutionMode executionMode = AkkaExecutionMode.Clustered,
string? clusterRole = null)
{
if (executionMode == AkkaExecutionMode.LocalTest)
{
// 非叢集模式:使用 GenericChildPerEntityParent
builder.WithActors((system, registry, resolver) =>
{
var parent = system.ActorOf(
GenericChildPerEntityParent.CreateProps(
new OrderMessageExtractor(),
entityId => resolver.Props<OrderActor>(entityId)),
"orders");
registry.Register<OrderActor>(parent);
});
}
else
{
// 叢集模式:使用 ShardRegion
builder.WithShardRegion<OrderActor>(
"orders",
(system, registry, resolver) =>
entityId => resolver.Props<OrderActor>(entityId),
new OrderMessageExtractor(),
new ShardOptions
{
StateStoreMode = StateStoreMode.DData,
Role = clusterRole
});
}
return builder;
}
}
組合多個參與者
建立一個便利的方法來註冊所有領域參與者:
public static class DomainActorHostingExtensions
{
/// <summary>
/// 新增所有訂單領域參與者,並支援分片。
/// </summary>
public static AkkaConfigurationBuilder WithOrderDomainActors(
this AkkaConfigurationBuilder builder,
AkkaExecutionMode executionMode = AkkaExecutionMode.Clustered,
string? clusterRole = null)
{
return builder
.WithOrderActor(executionMode, clusterRole)
.WithPaymentActor(executionMode, clusterRole)
.WithShipmentActor(executionMode, clusterRole)
.WithNotificationActor(); // 單例,不需要分片
}
}
使用 ITimeProvider 進行排程
將 ActorSystem 的 Scheduler 註冊為 ITimeProvider,用於可測試的基於時間的邏輯:
public static class SharedAkkaHostingExtensions
{
public static IServiceCollection AddAkkaWithTimeProvider(
this IServiceCollection services,
Action<AkkaConfigurationBuilder, IServiceProvider> configure)
{
// 使用 ActorSystem 的 Scheduler 註冊 ITimeProvider
services.AddSingleton<ITimeProvider>(sp =>
sp.GetRequiredService<ActorSystem>().Scheduler);
return services.ConfigureAkka((builder, sp) =>
{
configure(builder, sp);
});
}
}
// 在你的參與者中注入 ITimeProvider
public class SubscriptionActor : ReceiveActor
{
private readonly ITimeProvider _timeProvider;
public SubscriptionActor(ITimeProvider timeProvider)
{
_timeProvider = timeProvider;
// 使用 _timeProvider.GetUtcNow() 代替 DateTime.UtcNow
// 這允許測試控制時間
}
}
Akka.Reminders 整合
對於需要在重新啟動後保持的持久性排程任務,請使用 akka-reminders:
using Akka.Reminders;
using Akka.Reminders.Sql;
using Akka.Reminders.Sql.Configuration;
using Akka.Reminders.Storage;
public static class ReminderHostingExtensions
{
/// <summary>
/// 使用 PostgreSQL 儲存設定 akka-reminders。
/// </summary>
public static AkkaConfigurationBuilder WithPostgresReminders(
this AkkaConfigurationBuilder builder,
string connectionString,
string schemaName = "reminders",
string tableName = "scheduled_reminders",
bool autoInitialize = true)
{
return builder.WithLocalReminders(reminders => reminders
.WithResolver(sys => new GenericChildPerEntityResolver(sys))
.WithStorage(system =>
{
var settings = SqlReminderStorageSettings.CreatePostgreSql(
connectionString,
schemaName,
tableName,
autoInitialize);
return new SqlReminderStorage(settings, system);
})
.WithSettings(new ReminderSettings
{
MaxSlippage = TimeSpan.FromSeconds(30),
MaxDeliveryAttempts = 3,
RetryBackoffBase = TimeSpan.FromSeconds(10)
}));
}
/// <summary>
/// 使用記憶體儲存設定 akka-reminders 用於測試。
/// </summary>
public static AkkaConfigurationBuilder WithInMemoryReminders(
this AkkaConfigurationBuilder builder)
{
return builder.WithLocalReminders(reminders => reminders
.WithResolver(sys => new GenericChildPerEntityResolver(sys))
.WithStorage(system => new InMemoryReminderStorage())
.WithSettings(new ReminderSettings
{
MaxSlippage = TimeSpan.FromSeconds(1),
MaxDeliveryAttempts = 3,
RetryBackoffBase = TimeSpan.FromMilliseconds(100)
}));
}
}
用於 Child-Per-Entity 的自訂提醒解析器
將提醒回呼路由到 GenericChildPerEntityParent 參與者:
using Akka.Actor;
using Akka.Hosting;
using Akka.Reminders;
/// <summary>
/// 將提醒目標解析為 GenericChildPerEntityParent 參與者。
/// </summary>
public sealed class GenericChildPerEntityResolver : IReminderActorResolver
{
private readonly ActorSystem _system;
public GenericChildPerEntityResolver(ActorSystem system)
{
_system = system;
}
public IActorRef ResolveActorRef(ReminderEntry entry)
{
var registry = ActorRegistry.For(_system);
return entry.Key switch
{
var k when k.StartsWith("order-") =>
registry.Get<OrderActor>(),
var k when k.StartsWith("subscription-") =>
registry.Get<SubscriptionActor>(),
_ => throw new InvalidOperationException(
$"未知的提醒金鑰格式:{entry.Key}")
};
}
}
單例參與者(不分片)
對於只需要一個實例的參與者:
public static AkkaConfigurationBuilder WithEmailSenderActor(
this AkkaConfigurationBuilder builder)
{
return builder.WithActors((system, registry, resolver) =>
{
var actor = system.ActorOf(
resolver.Props<EmailSenderActor>(),
"email-sender");
registry.Register<EmailSenderActor>(actor);
});
}
用於註冊表的標記類型
當你需要參考已註冊為父參與者的參與者時:
/// <summary>
/// ActorRegistry 的標記類型,用於取得訂單管理員
/// (OrderActor 的 GenericChildPerEntityParent)。
/// </summary>
public sealed class OrderManagerActor;
// 在擴充方法中使用
registry.Register<OrderManagerActor>(parent);
// 在控制器/服務中使用
public class OrderService
{
private readonly IActorRef _orderManager;
public OrderService(IRequiredActor<OrderManagerActor> orderManager)
{
_orderManager = orderManager.ActorRef;
}
public async Task<OrderResponse> CreateOrder(CreateOrderCommand cmd)
{
return await _orderManager.Ask<OrderResponse>(cmd);
}
}
參與者中的 DI 範圍管理
參與者沒有自動的 DI 範圍。 與 ASP.NET 控制器不同(每個 HTTP 請求建立一個範圍),參與者是長期存在的。如果你需要範圍服務(如 DbContext),請注入 IServiceProvider 並手動建立範圍。
模式:每個訊息一個範圍
public sealed class OrderProcessingActor : ReceiveActor
{
private readonly IServiceProvider _serviceProvider;
private readonly IActorRef _notificationActor;
public OrderProcessingActor(
IServiceProvider serviceProvider,
IRequiredActor<NotificationActor> notificationActor)
{
_serviceProvider = serviceProvider;
_notificationActor = notificationActor.ActorRef;
ReceiveAsync<ProcessOrder>(HandleProcessOrder);
}
private async Task HandleProcessOrder(ProcessOrder msg)
{
// 為此訊息建立範圍 - 處理後會釋放
using var scope = _serviceProvider.CreateScope();
// 在範圍內解析範圍服務
var orderRepository = scope.ServiceProvider.GetRequiredService<IOrderRepository>();
var paymentService = scope.ServiceProvider.GetRequiredService<IPaymentService>();
var emailComposer = scope.ServiceProvider.GetRequiredService<IOrderEmailComposer>();
// 使用範圍服務執行工作
var order = await orderRepository.GetByIdAsync(msg.OrderId);
var payment = await paymentService.ProcessAsync(order);
// 範圍釋放時 DbContext 變更會提交
}
}
為什麼使用此模式
| 效益 | 說明 |
|---|---|
| 每個訊息都有全新的 DbContext | 避免訊息之間的過時實體追蹤 |
| 適當的釋放 | 每個訊息處理完後釋放資料庫連線 |
| 隔離性 | 一個訊息的錯誤不會破壞另一個訊息的狀態 |
| 可測試性 | 可以在測試中注入 Mock 的 IServiceProvider |
單例服務 - 直接注入
對於無狀態、執行緒安全的服務,直接注入(不需要範圍):
public sealed class NotificationActor : ReceiveActor
{
private readonly IEmailLinkGenerator _linkGenerator; // 單例 - 沒問題!
private readonly IMjmlTemplateRenderer _renderer; // 單例 - 沒問題!
public NotificationActor(
IEmailLinkGenerator linkGenerator,
IMjmlTemplateRenderer renderer)
{
_linkGenerator = linkGenerator;
_renderer = renderer;
}
}
摘要:DI 與參與者的最佳實踐
| 服務生命週期 | 注入方式 | 範例 |
|---|---|---|
| 單例(跨所有訊息共享) | 直接注入到建構函式 | ILogger<T>, IHttpClientFactory, IMapper |
| 範圍(每個訊息新的) | 注入 IServiceProvider 並建立範圍 | ApplicationDbContext, IOrderRepository |
| 暫時(每次解析時新建) | 通過範圍注入 IServiceProvider 或直接注入 | IOptionsSnapshot<T>, 輕量計算服務 |