This module provides Akka.Hosting
ease-of-use extension methods for Akka.Cluster
, Akka.Cluster.Sharding
, and Akka.Cluster.Tools
.
An extension method to add Akka.Cluster support to the ActorSystem
.
public static AkkaConfigurationBuilder WithClustering(
this AkkaConfigurationBuilder builder,
ClusterOptions options = null);
-
options
ClusterOptionsOptional. Akka.Cluster configuration parameters.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAkka("MyActorSystem", configurationBuilder =>
{
configurationBuilder
.WithRemoting("localhost", 8110)
.WithClustering(new ClusterOptions {
Roles = new[] { "myRole" },
SeedNodes = new[] { Address.Parse("akka.tcp://MyActorSystem@localhost:8110")},
SplitBrainResolver = 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.
The ClusterOptions.SplitBrainResolver property 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(new ClusterOptions {
SplitBrainResolver = new KeepMajorityOption{ Role = "myRole" },
});
});
In order to use LeaseMajorityOption
you will need to provide an instance of the option class of the Lease
module you're going to use in the LeaseMajorityOption.LeaseImplementation
property.
-
For
Akka.Coordination.KubernetesApi
, this is an instance ofAkka.Coordination.KubernetesApi.KubernetesLeaseOption
class.builder.Services.AddAkka("MyActorSystem", configurationBuilder => { var leaseOptions = new KubernetesLeaseOption(); configurationBuilder .WithClustering(new ClusterOptions { SplitBrainResolver = new LeaseMajorityOption{ LeaseImplementation = leaseOptions, }, }) .WithKubernetesLease(leaseOptions); });
-
For
Akka.Coordination.Azure
this is an instance ofAkka.Coordination.Azure.AzureLeaseOption
class.builder.Services.AddAkka("MyActorSystem", configurationBuilder => { var leaseOptions = new AzureLeaseOption { ConnectionString = "<Your-Azure-Blob-storage-connection-string>", ContainerName = "<Your-Azure-Blob-storage-container-name>"; }; configurationBuilder .WithClustering(new ClusterOptions { SplitBrainResolver = new LeaseMajorityOption{ LeaseImplementation = leaseOptions, }, }) .WithAzureLease(leaseOptions); });
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
.
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);
-
TKey
The type key to use to retrieve the
IActorRef
for thisShardRegion
from theActorRegistry
.
-
builder
AkkaConfigurationBuilderThe builder instance being configured.
-
typeName
stringThe 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 theSharding.ShardRegion
-
compositePropsFactory
Func<ActorSystem, IActorRegistry, Func<string, Props>>A delegate function that takes an
ActorSystem
and anActorRegistry
as parameters and returns aProps
factory. Used when theProps
factory either depends on another actor or needs to access theActorSystem
to set theProps
up. -
messageExtractor
IMessageExtractorAn
IMessageExtractor
interface implementation to extract the entity id, shard id, and the message to send to the entity from the incoming message. -
extractEntityId
ExtractEntityIdPartial 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 asUnhandled
messages on the event stream -
extractShardId
ExtractShardIdDelegate function to determine the shard id for an incoming message, only messages that passed the
extractEntityId
will be used -
shardOptions
ShardOptionsThe set of options for configuring
ClusterShardingSettings
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();
}
}
To use the cluster sharding lease feature, you will need to pass in the lease option into the shardOptions
parameter:
var leaseOptions = new AzureLeaseOption {
ConnectionString = "<Your-Azure-Blob-storage-connection-string>",
ContainerName = "<Your-Azure-Blob-storage-container-name>";
};
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{
LeaseImplementation = leaseOptions,
})
.WithAzureLease(leaseOptions);
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
.
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);
-
TKey
The type key to use to retrieve the
IActorRef
for thisShardRegion
from theActorRegistry
.
-
builder
AkkaConfigurationBuilderThe builder instance being configured.
-
typeName
stringThe name of the entity type
-
roleName
stringThe role of the Akka.Cluster member that is hosting the target
ShardRegion
. -
messageExtractor
IMessageExtractorAn
IMessageExtractor
interface implementation to extract the entity id, shard id, and the message to send to the entity from the incoming message. -
extractEntityId
ExtractEntityIdPartial 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 asUnhandled
messages on the event stream -
extractShardId
ExtractShardIdDelegate function to determine the shard id for an incoming message, only messages that passed the
extractEntityId
will be used
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);
-
builder
AkkaConfigurationBuilderThe builder instance being configured.
-
role
stringSpecifies which role
DistributedPubSub
will broadcast gossip to. If this value is left blank then ALL roles will be targeted.
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);
-
TKey
The key type to use for the
ActorRegistry
whencreateProxyToo
is set to true.
-
builder
AkkaConfigurationBuilderThe 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.
To use the cluster singleton lease feature, you will need to pass in the lease option into the options
parameter:
Props propsFactory(ActorSystem system, IActorRegistry registry, IDependencyResolver resolver)
=> Props.Create(() => new EchoActor());
var leaseOptions = new AzureLeaseOption {
ConnectionString = "<Your-Azure-Blob-storage-connection-string>",
ContainerName = "<Your-Azure-Blob-storage-container-name>";
};
configurationBuilder
.WithRemoting()
.WithClustering()
.WithSingleton<Echo>(
singletonName: "singleton",
propsFactory: propsFactory,
options: new ClusterSingletonOptions {
LeaseImplementation = leaseOptions,
})
.WithAzureLease(leaseOptions);
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);
-
TKey
The key type to use for the
ActorRegistry
.
-
builder
AkkaConfigurationBuilderThe builder instance being configured.
-
singletonName
stringThe name of this singleton instance. Will also be used in the
ActorPath
for theClusterSingletonManager
and optionally, theClusterSingletonProxy
created by this method. -
options
ClusterSingletonOptionsOptional. The set of options for configuring the
ClusterSingletonProxy
. -
singletonManagerPath
stringOptional. 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.
Configures a Cluster Client ClusterClientReceptionist
for the ActorSystem
public static AkkaConfigurationBuilder WithClusterClientReceptionist(
this AkkaConfigurationBuilder builder,
string name = "receptionist",
string role = null);
-
builder
AkkaConfigurationBuilderThe 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.
Creates a Cluster Client and adds it to the ActorRegistry
using the given TKey
.
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);
-
builder
AkkaConfigurationBuilderThe builder instance being configured.
-
initialContacts
IList, IEnumerableList of
ClusterClientReceptionist
actor path inActorPath
orstring
form that will be used as a seed to discover all of the receptionists in the cluster. -
initialContactAddresses
IEnumerableList of node addresses where the
ClusterClientReceptionist
are located that will be used as seed to discover all of the receptionists in the cluster. -
receptionistActorName
stringThe name of the
ClusterClientReceptionist
actor. Defaults to "receptionist"