你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

枚举 Service Fabric Reliable Actors

Reliable Actors 允许客户端枚举有关该服务托管的执行组件的元数据。 由于执行组件服务是已分区的有状态服务,因此将按分区执行枚举。 因为每个分区可能包含许多执行组件,所以枚举以一组分页结果的形式返回。 将循环读取这些页面,直到读取所有页面。 以下示例显示如何在参与者服务的一个分区中创建包含所有活动参与者的列表:

IActorService actorServiceProxy = ActorServiceProxy.Create(
    new Uri("fabric:/MyApp/MyService"), partitionKey);

ContinuationToken continuationToken = null;
List<ActorInformation> activeActors = new List<ActorInformation>();

do
{
    PagedResult<ActorInformation> page = await actorServiceProxy.GetActorsAsync(continuationToken, cancellationToken);

    activeActors.AddRange(page.Items.Where(x => x.IsActive));

    continuationToken = page.ContinuationToken;
}
while (continuationToken != null);
ActorService actorServiceProxy = ActorServiceProxy.create(
    new URI("fabric:/MyApp/MyService"), partitionKey);

ContinuationToken continuationToken = null;
List<ActorInformation> activeActors = new ArrayList<ActorInformation>();

do
{
    PagedResult<ActorInformation> page = actorServiceProxy.getActorsAsync(continuationToken);

    while(ActorInformation x: page.getItems())
    {
         if(x.isActive()){
              activeActors.add(x);
         }
    }

    continuationToken = page.getContinuationToken();
}
while (continuationToken != null);

虽然上述代码将检索给定分区中的所有参与者,但偶尔需要查询每个分区上所有参与者(活动的或非活动的)的 ID。 这应该通过异常处理完成,因为它是一个相当繁重的任务。

以下示例显示如何查询服务的分区,并结合上面的示例循环访问每个分区,以在 Service Fabric 应用程序中生成服务中所有活动和非活动参与者的列表:


var serviceName = new Uri("fabric:/MyApp/MyService");

//As the FabricClient is expensive to create, it should be shared as much as possible
FabricClient fabricClient = new();

//List each of the service's partitions
ServicePartitionList partitions = await fabricClient.QueryManager.GetPartitionListAsync(serviceName);

List<Guid> actorIds = new();

foreach(var partition in partitions)
{
    //Retrieve the partition information
    Int64RangePartitionInformation partitionInformation = (Int64RangePartitionInformation)partition.PartitionInformation; //Actors are restricted to the uniform Int64 scheme per https://learn.microsoft.com/azure/service-fabric/service-fabric-reliable-actors-introduction#distribution-and-failover
    IActorService actorServiceProxy = ActorServiceProxy.Create(serviceName, partitionInformation.LowKey);
    
    ContinuationToken? continuationToken = null;
    
    do 
    {
        var page = await actorServiceProxy.GetActorsAsync(continuationToken, cancellationToken);
        actorIds.AddRange(page.Items.Select(actor => actor.ActorId.GetGuidId());
        continuationToken = page.ContinuationToken;
    } while (continuationToken != null);
}

return actorIds;

后续步骤