private static ActorSystemConfig GetSystemConfig() => ActorSystemConfig .Setup() .WithDeadLetterThrottleCount(3) .WithDeadLetterThrottleInterval(TimeSpan.FromSeconds(1)) .WithDeveloperSupervisionLogging(true);
/// <summary> /// Configures the <see cref="ActorSystem"/> service in the <see cref="ServiceCollection"/>. /// </summary> /// <param name="builder">The <see cref="IHostBuilder"/>.</param> /// <returns>The builder for continuation.</returns> public static IHostBuilder AddActorSystem(this IHostBuilder builder) => builder.ConfigureServices(_ => _ .AddSingleton(provider => new ActorSystem(ActorSystemConfig.Setup()) .WithServiceProvider(provider) .WithRemote(GrpcNetRemoteConfig .BindToLocalhost() .WithProtoMessages(provider.GetRequiredService <IProtobufFileDescriptors>().All.ToArray())) .WithCluster(ClusterConfig.Setup( "Dolittle", new TestProvider(new TestProviderOptions(), new InMemAgent()), new PartitionIdentityLookup()) .WithDiscoveredClusterKinds(provider))) .AddSingleton(provider => provider.GetRequiredService <ActorSystem>().Root.WithTracing()) .AddSingleton(provider => provider.GetRequiredService <ActorSystem>().Cluster()));
private static async Task Main() { Log.SetLoggerFactory(LoggerFactory.Create(c => c .SetMinimumLevel(LogLevel.Information) .AddConsole() ) ); #if NETCORE AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); #endif Console.WriteLine("Enter 0 to use GrpcCore provider"); Console.WriteLine("Enter 1 to use GrpcNet provider"); if (!int.TryParse(Console.ReadLine(), out var provider)) { provider = 0; } Console.WriteLine("Enter Advertised Host (Enter = localhost)"); var advertisedHost = Console.ReadLine().Trim(); if (string.IsNullOrEmpty(advertisedHost)) { advertisedHost = "127.0.0.1"; } var actorSystemConfig = new ActorSystemConfig() .WithDeadLetterThrottleCount(10) .WithDeadLetterThrottleInterval(TimeSpan.FromSeconds(2)); var system = new ActorSystem(actorSystemConfig); var context = new RootContext(system); IRemote remote; if (provider == 0) { var remoteConfig = GrpcCoreRemoteConfig .BindTo(advertisedHost, 12000) .WithProtoMessages(ProtosReflection.Descriptor) .WithRemoteKind("echo", Props.FromProducer(() => new EchoActor())); remote = new GrpcCoreRemote(system, remoteConfig); } else { var remoteConfig = GrpcNetRemoteConfig .BindTo(advertisedHost, 12000) .WithChannelOptions(new GrpcChannelOptions { CompressionProviders = new[] { new GzipCompressionProvider(CompressionLevel.Fastest) } } ) .WithProtoMessages(ProtosReflection.Descriptor) .WithRemoteKind("echo", Props.FromProducer(() => new EchoActor())); remote = new GrpcNetRemote(system, remoteConfig); } await remote.StartAsync(); context.SpawnNamed(Props.FromProducer(() => new EchoActor()), "remote"); Console.ReadLine(); await remote.ShutdownAsync(); }
public static IHostBuilder UseProtoActor(this IHostBuilder host, Func <ActorSystemConfig, ActorSystemConfig> configFunc, Func <ActorSystem, ActorSystem> sysFunc, ProtoActorHostedServiceStart akkaHostedServiceStart) { host.ConfigureServices((context, services) => { services.AddSingleton(akkaHostedServiceStart); services.AddSingleton(sp => sysFunc(new ActorSystem(configFunc?.Invoke(ActorSystemConfig.Setup())) .WithServiceProvider(sp))); services.AddSingleton(typeof(IPropsFactory <>), typeof(PropsFactory <>)); services.AddHostedService <ProtoActorHostedService>(); services.AddSingleton(sp => (IRootContext) new RootContext(sp.GetService <ActorSystem>())); }); return(host); }
private static async Task Main() { Log.SetLoggerFactory(LoggerFactory.Create(c => c .SetMinimumLevel(LogLevel.Information) .AddConsole() ) ); var logger = Log.CreateLogger <Program>(); #if NETCORE AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); #endif Console.WriteLine("Enter 0 to use GrpcCore provider"); Console.WriteLine("Enter 1 to use GrpcNet provider"); if (!int.TryParse(Console.ReadLine(), out var provider)) { provider = 0; } Console.WriteLine("Enter client advertised host (Enter = localhost)"); var advertisedHost = Console.ReadLine().Trim(); if (string.IsNullOrEmpty(advertisedHost)) { advertisedHost = "127.0.0.1"; } Console.WriteLine("Enter remote advertised host (Enter = localhost)"); var remoteAddress = Console.ReadLine().Trim(); if (string.IsNullOrEmpty(remoteAddress)) { remoteAddress = "127.0.0.1"; } var actorSystemConfig = new ActorSystemConfig() .WithDeadLetterThrottleCount(10) .WithDeadLetterThrottleInterval(TimeSpan.FromSeconds(2)); var system = new ActorSystem(actorSystemConfig); var context = new RootContext(system); IRemote remote; if (provider == 0) { var remoteConfig = GrpcCoreRemoteConfig .BindTo(advertisedHost) .WithProtoMessages(ProtosReflection.Descriptor); remote = new GrpcCoreRemote(system, remoteConfig); } else { var remoteConfig = GrpcNetRemoteConfig .BindTo(advertisedHost) .WithChannelOptions(new GrpcChannelOptions { CompressionProviders = new[] { new GzipCompressionProvider(CompressionLevel.Fastest) } } ) .WithProtoMessages(ProtosReflection.Descriptor); remote = new GrpcNetRemote(system, remoteConfig); } await remote.StartAsync(); var messageCount = 1000000; var cancellationTokenSource = new CancellationTokenSource(); _ = SafeTask.Run(async() => { while (!cancellationTokenSource.IsCancellationRequested) { var semaphore = new SemaphoreSlim(0); var props = Props.FromProducer(() => new LocalActor(0, messageCount, semaphore)); var pid = context.Spawn(props); try { var actorPidResponse = await remote.SpawnAsync($"{remoteAddress}:12000", "echo", TimeSpan.FromSeconds(1)); if (actorPidResponse.StatusCode == (int)ResponseStatusCode.OK) { var remotePid = actorPidResponse.Pid; await context.RequestAsync <Start>(remotePid, new StartRemote { Sender = pid }, TimeSpan.FromSeconds(1) ); var stopWatch = new Stopwatch(); stopWatch.Start(); Console.WriteLine("Starting to send"); var msg = new Ping(); for (var i = 0; i < messageCount; i++) { context.Send(remotePid, msg); } var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token, new CancellationTokenSource(2000).Token ); await semaphore.WaitAsync(linkedTokenSource.Token); stopWatch.Stop(); var elapsed = stopWatch.Elapsed; Console.WriteLine("Elapsed {0}", elapsed); var t = messageCount * 2.0 / elapsed.TotalMilliseconds * 1000; Console.Clear(); Console.WriteLine("Throughput {0} msg / sec", t); await context.StopAsync(remotePid); } } catch (OperationCanceledException) { await Task.Delay(1000); } catch (Exception e) { logger?.LogError(e, "Error"); await Task.Delay(5000); } await context.PoisonAsync(pid); } }, cancellationTokenSource.Token ); Console.ReadLine(); cancellationTokenSource.Cancel(); await Task.Delay(1000); Console.WriteLine("Press enter to quit"); Console.ReadLine(); await remote.ShutdownAsync(); }
public static void Run() { var l = LoggerFactory.Create(x => x.AddConsole().SetMinimumLevel(LogLevel.Information)); Log.SetLoggerFactory(l); var config = ActorSystemConfig.Setup().WithMetricsProviders(new PrometheusConfigurator()); var remoteConfig = GrpcCoreRemoteConfig .BindToLocalhost() .WithProtoMessages(MessagesReflection.Descriptor); var clusterConfig = ClusterConfig .Setup("MyCluster", new ConsulProvider(new ConsulProviderConfig(), c => c.Address = new Uri("http://127.0.0.1:8500/")), new PartitionIdentityLookup() ); var system = new ActorSystem(config) .WithRemote(remoteConfig) .WithCluster(clusterConfig); system .Cluster() .StartMemberAsync(); var props = Props.FromProducer(() => new MyActor()); var config2 = ActorSystemConfig.Setup().WithMetricsProviders(new PrometheusConfigurator()); var remoteConfig2 = GrpcCoreRemoteConfig .BindToLocalhost() .WithProtoMessages(MessagesReflection.Descriptor); var clusterConfig2 = ClusterConfig .Setup("MyCluster", new ConsulProvider(new ConsulProviderConfig(), c => c.Address = new Uri("http://127.0.0.1:8500/")), new PartitionIdentityLookup() ) .WithClusterKind("somekind", props); var system2 = new ActorSystem(config2) .WithRemote(remoteConfig2) .WithCluster(clusterConfig2); system2 .Cluster() .StartMemberAsync(); _ = SafeTask.Run(async() => { var r = new Random(); while (true) { await Task.Delay(r.Next(1, 2000)); await system.Cluster().RequestAsync <SomeResponse>($"someactor{r.Next(1, 100)}", "somekind", new SomeRequest(), CancellationTokens.WithTimeout(5000) ); } } ); }
public async Task <Cluster> CreateCluster() { try { var actorSystemConfig = ActorSystemConfig.Setup(); if (_metricsProvider != null) { actorSystemConfig = actorSystemConfig .WithMetricsProviders(_metricsProvider); } var system = new ActorSystem(actorSystemConfig); _logger.LogInformation("Setting up Cluster"); _logger.LogInformation("ClusterName: " + _clusterSettings.ClusterName); _logger.LogInformation("PIDDatabaseName: " + _clusterSettings.PIDDatabaseName); _logger.LogInformation("PIDCollectionName: " + _clusterSettings.PIDCollectionName); var clusterProvider = _clusterProvider.CreateClusterProvider(_logger); //var identity = RedisIdentityLookup.GetIdentityLookup(_clusterSettings.ClusterName, _clusterSettings.Host, _clusterSettings.RedisPort); var identity = MongoIdentityLookup.GetIdentityLookup(_clusterSettings.ClusterName, _clusterSettings.PIDConnectionString, _clusterSettings.PIDCollectionName, _clusterSettings.PIDDatabaseName); var(clusterConfig, remoteConfig) = GenericClusterConfig.CreateClusterConfig(_clusterSettings, clusterProvider, identity, _descriptorProvider, _logger); if (_setupRootActors != null) { clusterConfig = _setupRootActors.AddRootActors(clusterConfig); } _ = new GrpcCoreRemote(system, remoteConfig); var cluster = new Cluster(system, clusterConfig); await cluster.StartMemberAsync().ConfigureAwait(false); if (this._subscriptionFactory != null) { _logger.LogInformation("Fire up subscriptions for system {id} {address}", system.Id, system.Address); await this._subscriptionFactory.FireUp(system).ConfigureAwait(false); } _ = SafeTask.Run(async() => { try { int counter = 0; while (!_cancellationTokenSource.IsCancellationRequested) { Member[] members = cluster.MemberList.GetAllMembers(); string[] clusterKinds = cluster.GetClusterKinds(); if (clusterKinds.Length == 0) { _logger.LogInformation("[SharedClusterWorker] clusterKinds {clusterKinds}", clusterKinds.Length); _logger.LogInformation("[SharedClusterWorker] Restarting"); _ = this.RestartMe(); break; } this.Connected = members.Length > 0; if (!this.Connected) { counter = 0; _logger.LogInformation("[SharedClusterWorker] Connected {Connected}", this.Connected); } if (this.Connected) { if (counter % 20 == 0) { _logger.LogDebug("[SharedClusterWorker] Members {@Members}", members.Select(m => m.ToLogString())); } counter++; } await Task.Delay(500); } } catch { // ignored } }, _cancellationTokenSource.Token); return(cluster); } catch (Exception ex) { _logger.LogError(ex, "SharedClusterWork failed"); throw; } }