Community编程与开发github.com

Akka.Hosting 参与者模式

用于使用 Akka.Hosting 构建实体参与者的模式——GenericChildPerEntityParent、消息提取器、集群分片抽象、akka-reminders 以及 ITimeProvider。同时支持本地测试和集群生产模式。

Akka.Hosting 参与者模式 是什么?

此技能提供了一套全面的模式和实用方法,用于在 Akka.NET 中使用 Akka.Hosting 构建实体参与者。它解决了如何编写既可运行在本地测试环境(无需集群开销)又可直接迁移到集群生产环境(使用 Akka.Cluster.Sharding)的参与者代码这一核心挑战。核心抽象包括:一个 GenericChildPerEntityParent 参与者,它在本地模拟分片语义;基于 IMessageExtractor 的统一消息路由;用于流畅配置的 Akka.Hosting 扩展方法;以及用于可测试性时间逻辑的 ITimeProvider 模式。此外,该技能通过 akka-reminders 集成了持久化调度任务,并提供了一种管理 DI 作用域的可靠模式(每个消息一个作用域),以确保像 DbContext 这样的作用域服务在参与者中能正确使用。它专为 Akka.NET 用户设计,可同时在非集群和集群模式下工作。

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

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

在你喜欢的 AI 中提问

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

文档

Akka.Hosting 参与者模式 是做什么的?

何时使用此技能

在以下情况下使用此技能:

  • 构建代表领域对象的实体参与者(用户、订单、发票等)
  • 需要参与者在单元测试(无集群)和生产环境(集群分片)中都能工作
  • 使用 akka-reminders 设置定时任务
  • 使用 Akka.Hosting 扩展方法注册参与者
  • 创建可复用的参与者配置模式

核心原则

  1. 执行模式抽象 —— 相同的参与者代码可在本地(测试)或集群(生产)中运行
  2. 用于本地的 GenericChildPerEntityParent —— 无需集群开销即可模拟分片语义
  3. 用于路由的消息提取器 —— 复用 Akka.Cluster.Sharding 的 IMessageExtractor 接口
  4. Akka.Hosting 扩展方法 —— 流畅且易于组合的配置
  5. 用于可测试性的 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));
        });
    }
}

消息提取器

创建实现 Akka.Cluster.Sharding 中 IMessageExtractor 的提取器:

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)
            }));
    }
}

自定义每个实体子参与者的提醒解析器

将提醒回调路由到 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 检索订单管理器的标记类型
/// (OrderActors 的 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 都是新的避免消息之间的过时实体跟踪
正确的释放每个消息后释放数据库连接
隔离性一个消息的错误不会破坏另一个消息的状态
可测试性可以在测试中注入模拟的 IServiceProvider

单例服务 —— 直接注入

对于无状态、线程安全的服务,直接注入(无需作用域):

public sealed class NotificationActor : ReceiveActor
{
    private readonly IEmailLinkGenerator _linkGenerator;  // 单例 —— 可以!
    private readonly IMjmlTemplateRenderer _renderer;     // 单例 —— 可以!

    public NotificationActor(
        IEmailLinkGenerator linkGenerator,
        IMjmlTemplateRenderer renderer)
    {
        _linkGenerator = linkGenerator;
        _renderer = renderer;

        Receive<SendNotification>(msg =>
        {
            // 使用直接注入的服务
            var link = _linkGenerator.Generate(msg.UserId);
            var html = _renderer.Render(msg.TemplateName, msg.Data);

            // 发送通知...
        });
    }

    // 不注入 DbContext、IOrderRepository 等 —— 它们是作用域服务
}

测试提示

在单元测试中设置 LocalTest 模式

[Fact]
public async Task Order_actor_should_handle_create_command()
{
    // 使用本地测试模式设置 ActorSystem
    using var host = await AkkaHost.CreateActorSystem("test-system", builder =>
    {
        builder.WithOrderActor(AkkaExecutionMode.LocalTest);
    });

    var registry = ActorRegistry.For(host);
    var orderManager = registry.Get<OrderActor>();

    var response = await orderManager.Ask<OrderResponse>(
        new CreateOrderCommand(OrderId.New()));

    Assert.NotNull(response);
}

模拟 ITimeProvider 以控制时间

[Fact]
public async Task Subscription_actor_should_expire_after_30_days()
{
    var mockTime = new Mock<ITimeProvider>();
    var now = DateTime.UtcNow;
    mockTime.Setup(t => t.GetUtcNow()).Returns(now);

    // 配置 DI 容器
    var services = new ServiceCollection();
    services.AddSingleton(mockTime.Object);
    services.AddAkkaWithTimeProvider("test", builder =>
    {
        builder.WithSubscriptionActor(AkkaExecutionMode.LocalTest);
    });

    var serviceProvider = services.BuildServiceProvider();

    // 在测试中推进时间
    mockTime.Setup(t => t.GetUtcNow()).Returns(now.AddDays(31));

    // 断言参与者做出相应反应...
}

使用 InMemoryReminders 进行测试

[Fact]
public async Task Reminder_should_fire_after_delay()
{
    using var host = await AkkaHost.CreateActorSystem("test", builder =>
    {
        builder.WithInMemoryReminders()
               .WithOrderDomainActors(AkkaExecutionMode.LocalTest);
    });

    var reminders = host.ActorSystem.ActorOf(
        Props.Create(() => new ReminderActor()));

    // 安排一个 1 秒后的提醒
    await reminders.Ask(new ScheduleReminder("order-123", TimeSpan.FromSeconds(1)));

    // 等待提醒触发
    var received = await reminders.Ask<ReminderFired>(
        new WaitForReminder("order-123", TimeSpan.FromSeconds(2)));

    Assert.NotNull(received);
}

Individual skills in this repo

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

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

相关技能