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);-
optionsClusterOptionsOptional. 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.KubernetesLeaseOptionclass.builder.Services.AddAkka("MyActorSystem", configurationBuilder => { var leaseOptions = new KubernetesLeaseOption(); configurationBuilder .WithClustering(new ClusterOptions { SplitBrainResolver = new LeaseMajorityOption{ LeaseImplementation = leaseOptions, }, }) .WithKubernetesLease(leaseOptions); });
-
For
Akka.Coordination.Azurethis is an instance ofAkka.Coordination.Azure.AzureLeaseOptionclass.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);-
TKeyThe type key to use to retrieve the
IActorReffor thisShardRegionfrom theActorRegistry.
-
builderAkkaConfigurationBuilderThe builder instance being configured.
-
typeNamestringThe name of the entity type
-
entityPropsFactoryFunc<string, Props>Function that, given an entity id, returns the
Actor.Propsof the entity actors that will be created by theSharding.ShardRegion -
compositePropsFactoryFunc<ActorSystem, IActorRegistry, Func<string, Props>>A delegate function that takes an
ActorSystemand anActorRegistryas parameters and returns aPropsfactory. Used when thePropsfactory either depends on another actor or needs to access theActorSystemto set thePropsup. -
messageExtractorIMessageExtractorAn
IMessageExtractorinterface implementation to extract the entity id, shard id, and the message to send to the entity from the incoming message. -
extractEntityIdExtractEntityIdPartial 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 asUnhandledmessages on the event stream -
extractShardIdExtractShardIdDelegate function to determine the shard id for an incoming message, only messages that passed the
extractEntityIdwill be used -
shardOptionsShardOptionsThe 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);-
TKeyThe type key to use to retrieve the
IActorReffor thisShardRegionfrom theActorRegistry.
-
builderAkkaConfigurationBuilderThe builder instance being configured.
-
typeNamestringThe name of the entity type
-
roleNamestringThe role of the Akka.Cluster member that is hosting the target
ShardRegion. -
messageExtractorIMessageExtractorAn
IMessageExtractorinterface implementation to extract the entity id, shard id, and the message to send to the entity from the incoming message. -
extractEntityIdExtractEntityIdPartial 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 asUnhandledmessages on the event stream -
extractShardIdExtractShardIdDelegate function to determine the shard id for an incoming message, only messages that passed the
extractEntityIdwill 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);-
builderAkkaConfigurationBuilderThe builder instance being configured.
-
rolestringSpecifies which role
DistributedPubSubwill 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);-
TKeyThe key type to use for the
ActorRegistrywhencreateProxyToois set to true.
-
builderAkkaConfigurationBuilderThe builder instance being configured.
-
singletonNamestring
The name of this singleton instance. Will also be used in the ActorPath for the ClusterSingletonManager and optionally, the ClusterSingletonProxy created by this method.
actorPropsProps
The underlying actor type. SHOULD NOT BE CREATED USING ClusterSingletonManager.Props
optionsClusterSingletonOptions
Optional. The set of options for configuring both the ClusterSingletonManager and optionally, the ClusterSingletonProxy.
createProxyToobool
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);-
TKeyThe key type to use for the
ActorRegistry.
-
builderAkkaConfigurationBuilderThe builder instance being configured.
-
singletonNamestringThe name of this singleton instance. Will also be used in the
ActorPathfor theClusterSingletonManagerand optionally, theClusterSingletonProxycreated by this method. -
optionsClusterSingletonOptionsOptional. The set of options for configuring the
ClusterSingletonProxy. -
singletonManagerPathstringOptional. By default Akka.Hosting will assume the
ClusterSingletonManageris 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);-
builderAkkaConfigurationBuilderThe builder instance being configured.
-
namestring
Actor name of the ClusterReceptionist actor under the system path, by default it is "/system/receptionist"
rolestring
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);-
builderAkkaConfigurationBuilderThe builder instance being configured.
-
initialContactsIList, IEnumerableList of
ClusterClientReceptionistactor path inActorPathorstringform that will be used as a seed to discover all of the receptionists in the cluster. -
initialContactAddressesIEnumerableList of node addresses where the
ClusterClientReceptionistare located that will be used as seed to discover all of the receptionists in the cluster. -
receptionistActorNamestringThe name of the
ClusterClientReceptionistactor. Defaults to "receptionist"