Skip to content

Latest commit

 

History

History
462 lines (321 loc) · 16.7 KB

File metadata and controls

462 lines (321 loc) · 16.7 KB

Akka.Cluster.Hosting

This module provides Akka.Hosting ease-of-use extension methods for Akka.Cluster, Akka.Cluster.Sharding, and Akka.Cluster.Tools.

Content

Akka.Cluster Extension Methods

WithClustering Method

An extension method to add Akka.Cluster support to the ActorSystem.

public static AkkaConfigurationBuilder WithClustering(
    this AkkaConfigurationBuilder builder, 
    ClusterOptions options = null, 
    SplitBrainResolverOption sbrOptions = null);

Parameters

  • options ClusterOptions

    Optional. Akka.Cluster configuration parameters.

  • sbrOptions SplitBrainResolverOption

    Optional. Split brain resolver configuration parameters. This can be an instance of one of these classes:

    • KeepMajorityOption
    • StaticQuorumOption
    • KeepOldestOption
    • LeaseMajorityOption

Example

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAkka("MyActorSystem", configurationBuilder =>
{
    configurationBuilder
        .WithRemoting("localhost", 8110)
        .WithClustering(
            options: new ClusterOptions { 
                Roles = new[] { "myRole" },
                SeedNodes = new[] { Address.Parse("akka.tcp://MyActorSystem@localhost:8110")}}
            sbrOptions: SplitBrainResolverOption.Default
        );
});

var app = builder.Build();
app.Run();

The code above will start Akka.Cluster with Akka.Remote at localhost domain port 8110 and joins itself through the configured SeedNodes to form a single node cluster. The ClusterOptions class lets you configure the node roles and the seed nodes it should join at start up.

Configure A Cluster With Split-Brain Resolver (SBR)

The sbrOptions parameter lets you configure a SBR. There are four different strategies that the SBR can use, to set one up you will need to pass in one of these class instances:

Strategy name Option class
Keep Majority KeepMajorityOption
Static-Quorum StaticQuorumOption
Keep Oldest KeepOldestOption
Lease Majority LeaseMajorityOption

You can also pass in SplitBrainResolverOption.Default for the default SBR setting that uses the Keep Majority strategy with no role defined.

builder.Services.AddAkka("MyActorSystem", configurationBuilder =>
{
    configurationBuilder
        .WithClustering(sbrOption: new KeepMajorityOption{ Role = "myRole" });
});

NOTE: Currently, in order to use LeaseMajorityOption you will need to provide the absolute HOCON path to the Lease module you're going to use in the LeaseMajorityOption.LeaseImplementation property. For Akka.Coordination.KubernetesApi this is akka.coordination.lease.kubernetes

Akka.Cluster.Sharding Extension Methods

WithShardRegion Method

An extension method to set up Cluster Sharding. Starts a ShardRegion actor for the given entity typeName and registers the ShardRegion IActorRef with TKey in the ActorRegistry for this ActorSystem.

Overloads

public static AkkaConfigurationBuilder WithShardRegion<TKey>(
    this AkkaConfigurationBuilder builder, 
    string typeName, 
    Func<string, Props> entityPropsFactory, 
    IMessageExtractor messageExtractor, 
    ShardOptions shardOptions);
public static AkkaConfigurationBuilder WithShardRegion<TKey>(
    this AkkaConfigurationBuilder builder,
    string typeName,
    Func<string, Props> entityPropsFactory, 
    ExtractEntityId extractEntityId, 
    ExtractShardId extractShardId,
    ShardOptions shardOptions);
public static AkkaConfigurationBuilder WithShardRegion<TKey>(
    this AkkaConfigurationBuilder builder,
    string typeName,
    Func<ActorSystem, IActorRegistry, Func<string, Props>> compositePropsFactory, 
    IMessageExtractor messageExtractor, 
    ShardOptions shardOptions);
public static AkkaConfigurationBuilder WithShardRegion<TKey>(
    this AkkaConfigurationBuilder builder,
    string typeName,
    Func<ActorSystem, IActorRegistry, Func<string, Props>> compositePropsFactory, 
    ExtractEntityId extractEntityId,
    ExtractShardId extractShardId, 
    ShardOptions shardOptions);

Type Parameters

  • TKey

    The type key to use to retrieve the IActorRef for this ShardRegion from the ActorRegistry.

Parameters

  • builder AkkaConfigurationBuilder

    The builder instance being configured.

  • typeName string

    The name of the entity type

  • entityPropsFactory Func<string, Props>

    Function that, given an entity id, returns the Actor.Props of the entity actors that will be created by the Sharding.ShardRegion

  • compositePropsFactory Func<ActorSystem, IActorRegistry, Func<string, Props>>

    A delegate function that takes an ActorSystem and an ActorRegistry as parameters and returns a Props factory. Used when the Props factory either depends on another actor or needs to access the ActorSystem to set the Props up.

  • messageExtractor IMessageExtractor

    An IMessageExtractor interface implementation to extract the entity id, shard id, and the message to send to the entity from the incoming message.

  • extractEntityId ExtractEntityId

    Partial delegate function to extract the entity id and the message to send to the entity from the incoming message, if the partial function does not match the message will be unhandled, i.e.posted as Unhandled messages on the event stream

  • extractShardId ExtractShardId

    Delegate function to determine the shard id for an incoming message, only messages that passed the extractEntityId will be used

  • shardOptions ShardOptions

    The set of options for configuring ClusterShardingSettings

Example

public class EchoActor : ReceiveActor
{
    private readonly string _entityId;
    public EchoActor(string entityId)
    {
        _entityId = entityId;
        ReceiveAny(message => {
            Sender.Tell($"{Self} rcv {message}");
        });
    }
}

public class Program
{
    private const int NumberOfShards = 5;
    
    private static Option<(string, object)> ExtractEntityId(object message)
        => message switch {
            string id => (id, id),
            _ => Option<(string, object)>.None
        };

    private static string? ExtractShardId(object message)
        => message switch {
            string id => (id.GetHashCode() % NumberOfShards).ToString(),
            _ => null
        };
        
    private static Props PropsFactory(string entityId)
        => Props.Create(() => new EchoActor(entityId));
        
    public static void Main(params string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        builder.Services.AddAkka("MyActorSystem", configurationBuilder =>
        {
            configurationBuilder
                .WithRemoting(hostname: "localhost", port: 8110)
                .WithClustering(new ClusterOptions{SeedNodes = new []{ Address.Parse("akka.tcp://MyActorSystem@localhost:8110"), }})
                .WithShardRegion<Echo>(
                    typeName: "myRegion",
                    entityPropsFactory: PropsFactory, 
                    extractEntityId: ExtractEntityId,
                    extractShardId: ExtractShardId,
                    shardOptions: new ShardOptions());
        });

        var app = builder.Build();

        app.MapGet("/", async (context) =>
        {
            var echo = context.RequestServices.GetRequiredService<ActorRegistry>().Get<Echo>();
            var body = await echo.Ask<string>(
                    message: context.TraceIdentifier, 
                    cancellationToken: context.RequestAborted)
                .ConfigureAwait(false);
            await context.Response.WriteAsync(body);
        });

        app.Run();    
    }
}

WithShardRegionProxy Method

An extension method to start a ShardRegion proxy actor that points to a ShardRegion hosted on a different role inside the cluster and registers the IActorRef with TKey in the ActorRegistry for this ActorSystem.

Overloads

public static AkkaConfigurationBuilder WithShardRegionProxy<TKey>(
    this AkkaConfigurationBuilder builder,
    string typeName, 
    string roleName, 
    ExtractEntityId extractEntityId, 
    ExtractShardId extractShardId);
public static AkkaConfigurationBuilder WithShardRegionProxy<TKey>(
    this AkkaConfigurationBuilder builder,
    string typeName, 
    string roleName,
     IMessageExtractor messageExtractor);

Type Parameters

  • TKey

    The type key to use to retrieve the IActorRef for this ShardRegion from the ActorRegistry.

Parameters

  • builder AkkaConfigurationBuilder

    The builder instance being configured.

  • typeName string

    The name of the entity type

  • roleName string

    The role of the Akka.Cluster member that is hosting the target ShardRegion.

  • messageExtractor IMessageExtractor

    An IMessageExtractor interface implementation to extract the entity id, shard id, and the message to send to the entity from the incoming message.

  • extractEntityId ExtractEntityId

    Partial delegate function to extract the entity id and the message to send to the entity from the incoming message, if the partial function does not match the message will be unhandled, i.e.posted as Unhandled messages on the event stream

  • extractShardId ExtractShardId

    Delegate function to determine the shard id for an incoming message, only messages that passed the extractEntityId will be used

Akka.Cluster.Tools Extension Methods

WithDistributedPubSub Method

An extension method to start Distributed Publish Subscribe on this node immediately upon ActorSystem startup. Stores the pub-sub mediator IActorRef in the ActorRegistry using the DistributedPubSub key.

public static AkkaConfigurationBuilder WithDistributedPubSub(
    this AkkaConfigurationBuilder builder,
    string role);

Parameters

  • builder AkkaConfigurationBuilder

    The builder instance being configured.

  • role string

    Specifies which role DistributedPubSub will broadcast gossip to. If this value is left blank then ALL roles will be targeted.

WithSingleton Method

An extension method to start Cluster Singleton. Creates a new Singleton Manager to host an actor created via actorProps.

If createProxyToo is set to true then this method will also create a ClusterSingletonProxy that will be added to the ActorRegistry using the key TKey. Otherwise this method will register nothing with the ActorRegistry.

public static AkkaConfigurationBuilder WithSingleton<TKey>(
    this AkkaConfigurationBuilder builder,
    string singletonName, 
    Props actorProps, 
    ClusterSingletonOptions options = null, 
    bool createProxyToo = true);

Type Parameters

  • TKey

    The key type to use for the ActorRegistry when createProxyToo is set to true.

Parameters

  • builder AkkaConfigurationBuilder

    The builder instance being configured.

  • singletonName string

The name of this singleton instance. Will also be used in the ActorPath for the ClusterSingletonManager and optionally, the ClusterSingletonProxy created by this method.

  • actorProps Props

The underlying actor type. SHOULD NOT BE CREATED USING ClusterSingletonManager.Props

  • options ClusterSingletonOptions

Optional. The set of options for configuring both the ClusterSingletonManager and optionally, the ClusterSingletonProxy.

  • createProxyToo bool

When set to true, creates a ClusterSingletonProxy that automatically points to the ClusterSingletonManager created by this method.

WithSingletonProxy Method

An extension method to create a Cluster Singleton Proxy and adds it to the ActorRegistry using the given TKey.

public static AkkaConfigurationBuilder WithSingletonProxy<TKey>(
    this AkkaConfigurationBuilder builder,
    string singletonName, 
    ClusterSingletonOptions options = null, 
    string singletonManagerPath = null);

Type Parameters

  • TKey

    The key type to use for the ActorRegistry.

Parameters

  • builder AkkaConfigurationBuilder

    The builder instance being configured.

  • singletonName string

    The name of this singleton instance. Will also be used in the ActorPath for the ClusterSingletonManager and optionally, the ClusterSingletonProxy created by this method.

  • options ClusterSingletonOptions

    Optional. The set of options for configuring the ClusterSingletonProxy.

  • singletonManagerPath string

    Optional. By default Akka.Hosting will assume the ClusterSingletonManager is hosted at "/user/{singletonName}" - but if for some reason the path is different you can use this property to override that value.

WithClusterClientReceptionist Method

Configures a Cluster Client ClusterClientReceptionist for the ActorSystem

public static AkkaConfigurationBuilder WithClusterClientReceptionist(
    this AkkaConfigurationBuilder builder,
    string name = "receptionist",
    string role = null);

Parameters

  • builder AkkaConfigurationBuilder

    The builder instance being configured.

  • name string

Actor name of the ClusterReceptionist actor under the system path, by default it is "/system/receptionist"

  • role string

Checks that the receptionist only start on members tagged with this role. All members are used if set to null.

WithClusterClient Method

Creates a Cluster Client and adds it to the ActorRegistry using the given TKey.

Overloads

public static AkkaConfigurationBuilder WithClusterClient<TKey>(
    this AkkaConfigurationBuilder builder,
    IList<ActorPath> initialContacts);
public static AkkaConfigurationBuilder WithClusterClient<TKey>(
    this AkkaConfigurationBuilder builder,
    IEnumerable<Address> initialContactAddresses,
    string receptionistActorName = "receptionist");
public static AkkaConfigurationBuilder WithClusterClient<TKey>(
    this AkkaConfigurationBuilder builder,
    IEnumerable<string> initialContacts);

Parameters

  • builder AkkaConfigurationBuilder

    The builder instance being configured.

  • initialContacts IList, IEnumerable

    List of ClusterClientReceptionist actor path in ActorPath or string form that will be used as a seed to discover all of the receptionists in the cluster.

  • initialContactAddresses IEnumerable

    List of node addresses where the ClusterClientReceptionist are located that will be used as seed to discover all of the receptionists in the cluster.

  • receptionistActorName string

    The name of the ClusterClientReceptionist actor. Defaults to "receptionist"