如何在单个服务中托管多个 Service Fabric Actor 类型?

How can I host multiple Service Fabric Actor Types inside a single service?

我读过 here 应该可以在同一个服务中托管紧密耦合的 ActorType,但我似乎无法找到关于具体操作方法的任何文档。

我认为我可能需要创建我自己的 ActorService 实例并将上下文传递给它,但我没有看到能够从文档中找到正确的 API。

有人可以分享示例吗?

有点,但不是真的。您可以在同一个 应用程序 中拥有多个参与者类型。看起来它们在 Visual Studio 中属于同一个服务,但实际上它们是作为单独的服务部署的。如果你愿意,请耐心等待我......

所以你可以像这样注册多个演员:

internal static class Program
{
    private static void Main()
    {
        ActorRuntime.RegisterActorAsync<Actor1>().GetAwaiter().GetResult();
        ActorRuntime.RegisterActorAsync<Actor2>().GetAwaiter().GetResult();

        Thread.Sleep(Timeout.Infinite);
    }
}

太好了,我有多种演员类型。这行得通,你可以这样做。

但您想知道如何它是如何工作的!嗯,这只是这个的简化版本:

internal static class Program
{
    private static void Main()
    {
        ActorRuntime.RegisterActorAsync<Actor1>(
            (context, actorType) => new ActorService(context, actorType, () => new Actor1())).GetAwaiter().GetResult();

        ActorRuntime.RegisterActorAsync<Actor2>(
            (context, actorType) => new ActorService(context, actorType, () => new Actor2())).GetAwaiter().GetResult();

        Thread.Sleep(Timeout.Infinite);
    }
}

这更能说明实际发生的情况,因为您在这里看到我现在有两个服务。那么这是怎么回事?

秘密就在ActorRuntime。它比 ServiceRuntime(您通常在其中注册 Reliable Services)做的工作多一点。 Actor 框架构建过程代表您执行一些魔法,在您的应用程序中为每个 actor 类型配置服务类型和默认服务实例。您可以在 ApplicationManifest.xml 中看到这一点,其中构建工具为您设置了默认服务:

<DefaultServices>
  <Service Name="Actor1ActorService" GeneratedIdRef="3262c188-3eee-44c5-9d1e-d2c2a2685f89|Persisted">
     <StatefulService ServiceTypeName="Actor1ActorServiceType" TargetReplicaSetSize="[Actor1ActorService_TargetReplicaSetSize]" MinReplicaSetSize="[Actor1ActorService_MinReplicaSetSize]">
        <UniformInt64Partition PartitionCount="[Actor1ActorService_PartitionCount]" LowKey="-9223372036854775808" HighKey="9223372036854775807" />
     </StatefulService>
  </Service>
  <Service Name="Actor2ActorService" GeneratedIdRef="1bc66d2c-0479-4bb2-a9aa-3254030506f1|Persisted">
     <StatefulService ServiceTypeName="Actor2ActorServiceType" TargetReplicaSetSize="[Actor2ActorService_TargetReplicaSetSize]" MinReplicaSetSize="[Actor2ActorService_MinReplicaSetSize]">
        <UniformInt64Partition PartitionCount="[Actor2ActorService_PartitionCount]" LowKey="-9223372036854775808" HighKey="9223372036854775807" />
     </StatefulService>
  </Service>

例如,如果我采用上面定义的两种参与者类型并部署该应用程序,结果如下:

这些实际上是应用程序中独立的服务实例,每个服务实例都是不同的服务类型,所有这些都是自动为您生成的:

当然,因为它们是不同的服务实例,它们将像您通常期望的那样分布在集群中:

我会去更新那个文档。