Esempio n. 1
0
        private void CreateCoordinator()
        {
            var typeNames = new[]
            {
                "counter", "rebalancingCounter", "PersistentCounterEntities", "AnotherPersistentCounter",
                "PersistentCounter", "RebalancingPersistentCounter", "AutoMigrateRegionTest"
            };

            foreach (var typeName in typeNames)
            {
                var rebalanceEnabled = string.Equals(typeName, "rebalancing", StringComparison.InvariantCultureIgnoreCase);
                var singletonProps   = Props.Create(() => new BackoffSupervisor(
                                                        CoordinatorProps(typeName, rebalanceEnabled),
                                                        "coordinator",
                                                        TimeSpan.FromSeconds(5),
                                                        TimeSpan.FromSeconds(5),
                                                        0.1)).WithDeploy(Deploy.Local);

                Sys.ActorOf(ClusterSingletonManager.Props(
                                singletonProps,
                                PoisonPill.Instance,
                                ClusterSingletonManagerSettings.Create(Sys)),
                            typeName + "Coordinator");
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Static factory method for creating the a singleton manager and proxy
        /// of the <see cref="ClusterCommandActor"/>
        /// </summary>
        /// <param name="system">The <see cref="ActorSystem"/>within which to create the singleton</param>
        /// <returns>A tuple containing <see cref="Props"/> for the proxy and manager in a given system</returns>
        public static (Props proxy, Props manager) CreateSingleton(ActorSystem system, string role)
        {
            var managerSettings = ClusterSingletonManagerSettings
                                  .Create(system)
                                  .WithSingletonName("cluster-command")
                                  .WithRemovalMargin(TimeSpan.FromSeconds(2))
                                  .WithHandOverRetryInterval(TimeSpan.FromMilliseconds(200));

            managerSettings = role != null?managerSettings.WithRole(role) : managerSettings;

            var proxySettings = ClusterSingletonProxySettings
                                .Create(system)
                                .WithSingletonName("cluster-command-proxy")
                                .WithBufferSize(1000);

            proxySettings = role != null?proxySettings.WithRole(role) : proxySettings;

            var manager = ClusterSingletonManager.Props(
                Props.Create(() => new ClusterCommandActor()),
                PoisonPill.Instance,
                managerSettings
                );

            var proxy = ClusterSingletonProxy.Props(
                "/user/cluster-command",
                proxySettings
                );

            return(proxy : proxy, manager : manager);
        }
Esempio n. 3
0
        private static async Task Main()
        {
            Console.WriteLine("Starting sender system...");
            var system = ActorSystem.Create("ClusterSys", ConfigurationFactory.ParseString(File.ReadAllText("Akka.hocon")));

            Console.ReadKey();

            system.ActorOf(ClusterSingletonManager.Props(
                               Props.Create <SingletonActor>(),
                               PoisonPill.Instance,
                               ClusterSingletonManagerSettings.Create(system).WithRole("b")
                               ), "single");

            system.ActorOf(ClusterSingletonProxy.Props("/user/single",
                                                       ClusterSingletonProxySettings.Create(system).WithRole("b")),
                           "singleProxy").Tell("Hello to singletone!");

            var message  = "initial message";
            var mediator = DistributedPubSub.Get(system).Mediator;

            mediator.Tell(new Send("/user/invoker", "Remote hello to singleton!"));

            while (!message.Equals("Stop"))
            {
                Console.WriteLine("New message:");
                message = Console.ReadLine();

                mediator.Tell(new Send("/user/ping", message, false));
            }

            Console.WriteLine("Terminating system.");
            await system.Terminate();

            Console.WriteLine("Bye...");
        }
Esempio n. 4
0
        private void CreateCoordinator()
        {
            var typeNames = new[]
            {
                "counter", "rebalancingCounter", "RememberCounterEntities", "AnotherRememberCounter",
                "RememberCounter", "RebalancingRememberCounter", "AutoMigrateRememberRegionTest"
            };

            foreach (var typeName in typeNames)
            {
                var rebalanceEnabled = typeName.ToLowerInvariant().StartsWith("rebalancing");
                var rememberEnabled  = typeName.ToLowerInvariant().Contains("remember");
                var singletonProps   = BackoffSupervisor.Props(
                    CoordinatorProps(typeName, rebalanceEnabled, rememberEnabled),
                    "coordinator",
                    TimeSpan.FromSeconds(5),
                    TimeSpan.FromSeconds(5),
                    0.1).WithDeploy(Deploy.Local);

                Sys.ActorOf(ClusterSingletonManager.Props(
                                singletonProps,
                                PoisonPill.Instance,
                                ClusterSingletonManagerSettings.Create(Sys)),
                            typeName + "Coordinator");
            }
        }
        public void ClusterSingleton_with_lease_should_stop_singleton_if_the_lease_fails_periodic_check()
        {
            var lifecycleProbe = CreateTestProbe();
            var settings       = NextSettings();

            Sys.ActorOf(
                ClusterSingletonManager.Props(Props.Create(() => new ImportantSingleton(lifecycleProbe.Ref)), PoisonPill.Instance, settings),
                settings.SingletonName);

            TestLease testLease = null;

            AwaitAssert(() =>
            {
                testLease = testLeaseExt.GetTestLease(LeaseNameFor(settings));
            }); // allow singleton manager to create the lease

            testLease.Probe.ExpectMsg(new TestLease.AcquireReq(leaseOwner));
            testLease.InitialPromise.SetResult(true);
            lifecycleProbe.ExpectMsg("preStart");
            var callback = testLease.GetCurrentCallback();

            callback(null);
            lifecycleProbe.ExpectMsg("postStop");
            testLease.Probe.ExpectMsg(new TestLease.ReleaseReq(leaseOwner));

            // should try and reacquire lease
            testLease.Probe.ExpectMsg(new TestLease.AcquireReq(leaseOwner));
            lifecycleProbe.ExpectMsg("preStart");
        }
Esempio n. 6
0
        public static DeploymentManager InitDeploymentManager(ActorSystem actorSystem, IMongoClient client, DataTransferManager manager, RepositoryApi api)
        {
            var repo = ClusterSingletonManager.Props(Props.Create(() => new DeploymentServerImpl(client, manager, api)),
                                                     ClusterSingletonManagerSettings.Create(actorSystem).WithRole("UpdateSystem"));

            return(new DeploymentManager(actorSystem.ActorOf(repo, DeploymentApi.DeploymentPath)));
        }
Esempio n. 7
0
        public static RepositoryManager InitRepositoryManager(ActorSystem actorSystem, IMongoClient client, DataTransferManager tranferManager)
        {
            var repo = ClusterSingletonManager.Props(Props.Create(() => new RepositoryManagerImpl(client, tranferManager)),
                                                     ClusterSingletonManagerSettings.Create(actorSystem).WithRole("UpdateSystem"));

            return(new RepositoryManager(actorSystem.ActorOf(repo, RepositoryApi.RepositoryPath)));
        }
Esempio n. 8
0
        public static ClusterStartupTask Apply(
            ActorSystem system, string taskName,
            Func <Task <Done> > task, TimeSpan taskTimeout,
            Option <string> role, TimeSpan minBackoff,
            TimeSpan maxBackoff, double randomBackoffFactor)
        {
            var startupTaskProps = Akka.Actor.Props.Create(
                () => new ClusterStartupTaskActor(
                    task, taskTimeout
                    )
                );
            var backoffProps = BackoffSupervisor.PropsWithSupervisorStrategy(
                startupTaskProps, taskName, minBackoff, maxBackoff, randomBackoffFactor, SupervisorStrategy.StoppingStrategy
                );
            var singletonProps = ClusterSingletonManager.Props(
                backoffProps, PoisonPill.Instance, ClusterSingletonManagerSettings.Create(system)
                );
            var singleton      = system.ActorOf(singletonProps, $"{taskName}-singleton");
            var singletonProxy = system.ActorOf(
                ClusterSingletonProxy.Props(
                    singletonManagerPath: singleton.Path.ToStringWithoutAddress(),
                    settings: ClusterSingletonProxySettings.Create(system).WithRole(role.Value)
                    ),
                $"{taskName}-singletonProxy"
                );

            return(new ClusterStartupTask(singletonProxy));
        }
Esempio n. 9
0
        public static void Main(string[] args)
        {
            if (!int.TryParse(args[0], out var nodeId))
            {
                Console.Error.WriteLine("Please supply a node ID");

                return;
            }

            var config = GetAkkaConfig(nodeId);

            using (var system = ActorSystem.Create("demo-cluster", config))
            {
                var cmd = PetabridgeCmd.Get(system);
                cmd.RegisterCommandPalette(ClusterCommands.Instance);
                cmd.Start();

                system.ActorOf(ClusterSingletonManager.Props(
                                   singletonProps: Props.Create <SenderActor>(),
                                   terminationMessage: PoisonPill.Instance,
                                   settings: ClusterSingletonManagerSettings.Create(system)),
                               name: "sender");

                var props = Props.Create <ReceiverActor>().WithRouter(FromConfig.Instance);
                system.ActorOf(props, "receivers");

                Console.ReadLine();
            }
        }
        public void ClusterSingleton_with_lease_should_retry_trying_to_get_lease_if_acquire_returns_fails()
        {
            var singletonProbe = CreateTestProbe();
            var settings       = NextSettings();

            Sys.ActorOf(
                ClusterSingletonManager.Props(Props.Create(() => new ImportantSingleton(singletonProbe.Ref)), PoisonPill.Instance, settings),
                settings.SingletonName);

            TestLease testLease = null;

            AwaitAssert(() =>
            {
                testLease = testLeaseExt.GetTestLease(LeaseNameFor(settings));
            }); // allow singleton manager to create the lease

            testLease.Probe.ExpectMsg(new TestLease.AcquireReq(leaseOwner));
            singletonProbe.ExpectNoMsg(shortDuration);
            TaskCompletionSource <bool> nextResponse = new TaskCompletionSource <bool>();

            testLease.SetNextAcquireResult(nextResponse.Task);
            testLease.InitialPromise.SetException(new TestException("no lease for you"));
            testLease.Probe.ExpectMsg(new TestLease.AcquireReq(leaseOwner));
            singletonProbe.ExpectNoMsg(shortDuration);
            nextResponse.SetResult(true);
            singletonProbe.ExpectMsg("preStart");
        }
Esempio n. 11
0
        public static IActorRef BootstrapSingleton <T>(this ActorSystem system, string name, string role = null) where T : ActorBase
        {
            var props = ClusterSingletonManager.Props(
                singletonProps: Props.Create <T>(),
                settings: new ClusterSingletonManagerSettings(name, role, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(3)));

            return(system.ActorOf(props, typeof(T).Name));
        }
Esempio n. 12
0
        public static IActorRef BootstrapSingleton <T>(this ActorSystem system, string role = null) where T : ActorBase
        {
            var props = ClusterSingletonManager.Props(
                singletonProps: Props.Create <T>(),
                settings: ClusterSingletonManagerSettings.Create(system).WithRole(role));

            return(system.ActorOf(props, typeof(T).Name));
        }
 private IActorRef CreateSingleton()
 {
     return(Sys.ActorOf(ClusterSingletonManager.Props(
                            singletonProps: Props.Create(() => new EchoActor(TestActor)),
                            terminationMessage: PoisonPill.Instance,
                            settings: ClusterSingletonManagerSettings.Create(Sys)),
                        name: "echo"));
 }
Esempio n. 14
0
 private IActorRef CreateSingleton()
 {
     return(Sys.ActorOf(ClusterSingletonManager.Props(
                            singletonProps: ClusterSingletonManagerDownedSpecConfig.Echo.Props(TestActor),
                            terminationMessage: PoisonPill.Instance,
                            settings: ClusterSingletonManagerSettings.Create(Sys)),
                        name: "echo"));
 }
        protected override void ConfigImpl()
        {
            Context.ActorOf(ClusterSingletonManager.Props(ConfigurationManagerActor.New(CurrentState.Repository),
                                                          ClusterSingletonManagerSettings.Create(Context.System)
                                                          .WithRole(RoleName)), "ConfigurationManager");

            SupervisorStrategy = SupervisorStrategy.DefaultStrategy;
        }
Esempio n. 16
0
 /// <summary>
 /// Initializes cluster singleton of the <see cref="WorkerManager"/> actor.
 /// </summary>
 /// <param name="system"></param>
 static void RunClusterSingletonSeed(ActorSystem system)
 {
     var aref = system.ActorOf(ClusterSingletonManager.Props(
                                   singletonProps: Props.Create(() => new WorkerManager()),
                                   terminationMessage: PoisonPill.Instance,
                                   settings: ClusterSingletonManagerSettings.Create(system)),
                               name: "manager");
 }
Esempio n. 17
0
 private void CreateSingleton()
 {
     Sys.ActorOf(ClusterSingletonManager.Props(
                     singletonProps: Props.Create(() => new Consumer(Queue, TestActor)),
                     terminationMessage: Consumer.End.Instance,
                     settings: ClusterSingletonManagerSettings.Create(Sys).WithRole("worker")),
                 name: "consumer");
 }
 public Props ManagerProps(ActorSystem system, Props childProps)
 {
     return(ClusterSingletonManager.Props(
                childProps,
                PoisonPill.Instance,
                ManagerSettings(system)
                ));
 }
 private IActorRef CreateSingleton()
 {
     return(Sys.ActorOf(ClusterSingletonManager.Props(
                            singletonProps: ClusterSingletonManagerLeaveSpecConfig.Echo.Props(TestActor),
                            terminationMessage: "stop",
                            settings: ClusterSingletonManagerSettings.Create(Sys)),
                        name: "echo"));
 }
Esempio n. 20
0
        static int Main(string[] args)
        {
            var mongoConnectionString = Environment.GetEnvironmentVariable("MONGO_CONNECTION_STR")?.Trim();

            if (string.IsNullOrEmpty(mongoConnectionString))
            {
                Console.WriteLine("ERROR! MongoDb connection string not provided. Can't start.");
                return(-1);
            }
            else
            {
                Console.WriteLine("Connecting to MongoDb at {0}", mongoConnectionString);
            }

            var config = File.ReadAllText("app.conf");
            var conf   = ConfigurationFactory.ParseString(config).WithFallback(GetMongoHocon(mongoConnectionString))
                         .WithFallback(ClusterSharding.DefaultConfig())
                         .WithFallback(DistributedPubSub.DefaultConfig());

            var actorSystem = ActorSystem.Create("AkkaPricing", conf.BootstrapFromDocker());
            var readJournal = actorSystem.ReadJournalFor <MongoDbReadJournal>(MongoDbReadJournal.Identifier);

            Cluster.Cluster.Get(actorSystem).RegisterOnMemberUp(() =>
            {
                var sharding = ClusterSharding.Get(actorSystem);

                var shardRegion = sharding.Start("priceAggregator",
                                                 s => Props.Create(() => new MatchAggregator(s, readJournal)),
                                                 ClusterShardingSettings.Create(actorSystem),
                                                 new StockShardMsgRouter());

                // used to seed pricing data
                var singleton = ClusterSingletonManager.Props(
                    Props.Create(() => new PriceInitiatorActor(readJournal, shardRegion)),
                    ClusterSingletonManagerSettings.Create(
                        actorSystem.Settings.Config.GetConfig("akka.cluster.price-singleton")));

                var mediator = DistributedPubSub.Get(actorSystem).Mediator;

                foreach (var stock in AvailableTickerSymbols.Symbols)
                {
                    actorSystem.ActorOf(Props.Create(() => new PriceVolumeViewActor(stock, shardRegion, mediator)),
                                        stock + "-view");
                }
            });

            // start Petabridge.Cmd (for external monitoring / supervision)
            var pbm = PetabridgeCmd.Get(actorSystem);

            pbm.RegisterCommandPalette(ClusterCommands.Instance);
            pbm.RegisterCommandPalette(ClusterShardingCommands.Instance);
            pbm.RegisterCommandPalette(RemoteCommands.Instance);
            pbm.Start();

            actorSystem.WhenTerminated.Wait();
            return(0);
        }
        static int Main(string[] args)
        {
            var config = File.ReadAllText("app.conf");
            var conf   = ConfigurationFactory.ParseString(config);

            var actorSystem = ActorSystem.Create("AkkaTrader", conf.BoostrapApplication(new AppBootstrapConfig(true, true)));

            var sharding = ClusterSharding.Get(actorSystem);


            var shardRegion = sharding.Start("priceAggregator",
                                             s => Props.Create(() => new MatchAggregator(s)),
                                             ClusterShardingSettings.Create(actorSystem),
                                             new StockShardMsgRouter());

            var priceInitiatorActor = actorSystem.ActorOf(ClusterSingletonManager.Props(Props.Create(() => new PriceInitiatorActor(shardRegion)),
                                                                                        ClusterSingletonManagerSettings.Create(actorSystem).WithRole("pricing-engine").WithSingletonName("priceInitiator")), "priceInitiator");

            var clientHandler =
                actorSystem.ActorOf(Props.Create(() => new ClientHandlerActor(shardRegion)), "subscriptions");

            // make ourselves available to ClusterClient at /user/subscriptions
            ClusterClientReceptionist.Get(actorSystem).RegisterService(clientHandler);

            Cluster.Cluster.Get(actorSystem).RegisterOnMemberUp(() =>
            {
                foreach (var ticker in AvailableTickerSymbols.Symbols)
                {
                    shardRegion.Tell(new Ping(ticker));
                }
            });

            // start Petabridge.Cmd (for external monitoring / supervision)
            var pbm = PetabridgeCmd.Get(actorSystem);

            void RegisterPalette(CommandPaletteHandler h)
            {
                if (pbm.RegisterCommandPalette(h))
                {
                    Console.WriteLine("Petabridge.Cmd - Registered {0}", h.Palette.ModuleName);
                }
                else
                {
                    Console.WriteLine("Petabridge.Cmd - DID NOT REGISTER {0}", h.Palette.ModuleName);
                }
            }

            RegisterPalette(ClusterCommands.Instance);
            RegisterPalette(RemoteCommands.Instance);
            RegisterPalette(ClusterShardingCommands.Instance);
            RegisterPalette(new PriceCommands(shardRegion));
            pbm.Start();

            actorSystem.WhenTerminated.Wait();
            return(0);
        }
Esempio n. 22
0
        static void Main()
        {
            var config = ConfigurationFactory.ParseString(configString).WithFallback(ClusterSingletonManager.DefaultConfig());
            var system = ActorSystem.Create("cluster-system", config);
            var server = system.ActorOf(ClusterSingletonManager.Props(
                                            singletonProps: Props.Create <Server>(),
                                            terminationMessage: PoisonPill.Instance,
                                            settings: ClusterSingletonManagerSettings.Create(system).WithRole("worker")),
                                        name: "consumer");

            Console.ReadKey();
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            var config = ConfigurationFactory.ParseString(File.ReadAllText("App.Akka.conf"));

            //
            // "{app-name} - akka.tcp://{actorysystem-name}@{hostname}:{port}"
            //
            Console.Title = $"{config.GetString("akka.system.app-name")}" +
                            $" - akka.tcp://{config.GetString("akka.system.actorsystem-name")}" +
                            $"@{config.GetString("akka.remote.dot-netty.tcp.hostname")}" +
                            $":{config.GetString("akka.remote.dot-netty.tcp.port")}";

            ActorSystem system = ActorSystem.Create("ClusterLab", config);

            system.ActorOf(ClusterSingletonManager
                           .Props(
                               singletonProps: MySingletonActor.Props(),
                               terminationMessage: PoisonPill.Instance,
                               settings: ClusterSingletonManagerSettings.Create(system)
                               .WithRole("Provider")),
                           name: "ConsumerSingleton");

            IActorRef singletonProxyActor = system.ActorOf(ClusterSingletonProxy
                                                           .Props(
                                                               singletonManagerPath: "/user/ConsumerSingleton",
                                                               settings: ClusterSingletonProxySettings.Create(system)
                                                               .WithRole("Provider")),
                                                           name: "ConsumerProxy");

            system.Scheduler.ScheduleTellRepeatedly(
                TimeSpan.Zero,
                TimeSpan.FromSeconds(4),
                singletonProxyActor,
                $"Message from process {Process.GetCurrentProcess().Id}",
                Nobody.Instance);

            //
            // TODO ClusterSingletonManagerSettings 세부 설정
            //  - WithHandOverRetryInterval
            //  - WithRemovalMargin
            //  - WithRole
            //  - WithSingletonName
            //

            Console.WriteLine();
            Console.WriteLine("NonSeedNode1 is running...");
            Console.WriteLine();

            Console.ReadLine();
        }
Esempio n. 24
0
        public void RegisterOnMemberUp()
        {
            Console.WriteLine(cluster.SelfAddress + "上线.....");

            var clusterSingletonManagerProps = ClusterSingletonManager.Props(
                singletonProps: SingleActor.CreateProps(this.actorSystem).WithRouter(new Akka.Routing.RoundRobinPool(5)),
                terminationMessage: PoisonPill.Instance,
                settings: ClusterSingletonManagerSettings.Create(ActorSystem));


            var singlet = ActorSystem.ActorOf(clusterSingletonManagerProps, name: "singletonManager");

            Console.WriteLine("singletonManager:{0}", singlet.Path.ToString());
        }
Esempio n. 25
0
        public void InitializeClusterSystem()
        {
            Program.ClusterSystem = ActorSystemFactory.LaunchClusterManager();

            GlobalContext.Properties["ipaddress"] = AppSettings.GetIpAddressFromConfig();

            Program.ClusterHelper = Program.ClusterSystem.ActorOf(Props.Create(() => new ClusterHelper()), ActorPaths.ClusterHelperActor.Name);

            Program.ClusterSystem.ActorOf(ClusterSingletonManager.Props(
                                              singletonProps: Props.Create(() => new JobManager()),                                        // Props used to create actor singleton
                                              terminationMessage: PoisonPill.Instance,                                                     // message used to stop actor gracefully
                                              settings: ClusterSingletonManagerSettings.Create(Program.ClusterSystem).WithRole("worker")), // cluster singleton manager settings
                                          name: "jobmanager");
        }
Esempio n. 26
0
        public ClusterShardingGuardian()
        {
            Receive <Start>(start =>
            {
                var settings = start.Settings;
                var encName  = Uri.EscapeDataString(start.TypeName);
                var coordinatorSingletonManagerName = CoordinatorSingletonManagerName(encName);
                var coordinatorPath = CoordinatorPath(encName);
                var shardRegion     = Context.Child(encName);

                if (Equals(shardRegion, ActorRefs.Nobody))
                {
                    var minBackoff        = settings.TunningParameters.CoordinatorFailureBackoff;
                    var maxBackoff        = new TimeSpan(minBackoff.Ticks * 5);
                    var coordinatorProps  = PersistentShardCoordinator.Props(start.TypeName, settings, start.AllocationStrategy);
                    var singletonProps    = Props.Create(() => new BackoffSupervisor(coordinatorProps, "coordinator", minBackoff, maxBackoff, 0.2)).WithDeploy(Deploy.Local);
                    var singletonSettings = settings.CoordinatorSingletonSettings.WithSingletonName("singleton").WithRole(settings.Role);

                    var shardCoordinatorSingleton = Context.ActorOf(ClusterSingletonManager.Props(singletonProps, PoisonPill.Instance, singletonSettings), coordinatorSingletonManagerName);
                }

                shardRegion = Context.ActorOf(ShardRegion.Props(
                                                  typeName: start.TypeName,
                                                  entityProps: start.EntityProps,
                                                  settings: settings,
                                                  coordinatorPath: coordinatorPath,
                                                  extractEntityId: start.IdExtractor,
                                                  extractShardId: start.ShardResolver,
                                                  handOffStopMessage: start.HandOffStopMessage), encName);

                Sender.Tell(new Started(shardRegion));
            });

            Receive <StartProxy>(startProxy =>
            {
                var settings = startProxy.Settings;
                var encName  = Uri.EscapeDataString(startProxy.TypeName);
                var coordinatorSingletonManagerName = CoordinatorSingletonManagerName(encName);
                var coordinatorPath = CoordinatorPath(encName);

                var shardRegion = Context.ActorOf(ShardRegion.ProxyProps(
                                                      typeName: startProxy.TypeName,
                                                      settings: settings,
                                                      coordinatorPath: coordinatorPath,
                                                      extractEntityId: startProxy.ExtractEntityId,
                                                      extractShardId: startProxy.ExtractShardId), encName);

                Sender.Tell(new Started(shardRegion));
            });
        }
 private IActorRef CreateSingleton()
 {
     /**
      * system.actorOf(ClusterSingletonManager.props(
      * singletonProps = Props(classOf[Echo], testActor),
      * terminationMessage = PoisonPill,
      * settings = ClusterSingletonManagerSettings(system)),
      * name = "echo")
      */
     return(Sys.ActorOf(ClusterSingletonManager.Props(
                            singletonProps: Props.Create(() => new Echo(TestActor)),
                            terminationMessage: PoisonPill.Instance,
                            settings: ClusterSingletonManagerSettings.Create(Sys)),
                        name: "echo"));
 }
Esempio n. 28
0
        static void Main()
        {
            var config = ConfigurationFactory.ParseString(configString).WithFallback(ClusterSingletonManager.DefaultConfig());
            var system = ActorSystem.Create("cluster-system", config);
            var server = system.ActorOf(ClusterSingletonManager.Props(
                                            singletonProps: Props.Create <Server>(),
                                            terminationMessage: PoisonPill.Instance,
                                            settings: ClusterSingletonManagerSettings.Create(system).WithRole("worker")),
                                        name: "consumer");

            Thread.Sleep(10000);
            var s = Address.Parse("akka.tcp://cluster-system@localhost:5001/");

            Cluster.Get(system).Leave(s);
            Console.ReadKey();
        }
Esempio n. 29
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello from MemoryWallet!");

            var system = DI.Provider.GetService <ActorSystem>();

            var logger = system.Log;

            logger.Info($"Joining cluster {system.Name}");

            // Singleton actor that keeps book of record of a player
            system.ActorOf(ClusterSingletonManager.Props(
                               singletonProps: PlayerBook.Props(),
                               terminationMessage: PoisonPill.Instance,
                               settings: ClusterSingletonManagerSettings.Create(system).WithRole("player-manager")
                               ), "playerbook");

            system.ActorOf(ClusterSingletonProxy.Props(
                               singletonManagerPath: "/user/playerbook",
                               settings: ClusterSingletonProxySettings.Create(system)
                               .WithRole("player-manager")),
                           name: "playerbook-proxy");

            // Register web hub across cluster
            var hub = system.ActorOf(Props.Empty.WithRouter(FromConfig.Instance), "hub");

            // create local player manager instances with router.
            var pm = system.ActorOf(PlayerManagerActor.Props(), "player-manager");

//            var pm = system.ActorOf(
//                PlayerManagerActor.Props().WithRouter(FromConfig.Instance),
//                "player-manager");

            hub.Tell("dsadsada");

            pm.Tell(new PlayerManagerActor.HelloWorld("hello world"));

            logger.Info($"{pm.Path} created.");



            Console.ReadLine();

            CoordinatedShutdown.Get(system)
            .Run(CoordinatedShutdown.ClrExitReason.Instance)
            .Wait();
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            var config    = ConfigurationFactory.ParseString(File.ReadAllText("app.conf")).BootstrapFromDocker();
            var bootstrap = BootstrapSetup.Create()
                            .WithConfig(config)                                        // load HOCON
                            .WithActorRefProvider(ProviderSelection.Cluster.Instance); // launch Akka.Cluster

            // N.B. `WithActorRefProvider` isn't actually needed here - the HOCON file already specifies Akka.Cluster

            // enable DI support inside this ActorSystem, if needed
            var diSetup = ServiceProviderSetup.Create(_serviceProvider);

            // merge this setup (and any others) together into ActorSystemSetup
            var actorSystemSetup = bootstrap.And(diSetup);

            ThreadPool.GetMinThreads(out var workerThreads, out var completionThreads);
            Console.WriteLine("Min threads: {0}, Min I/O threads: {1}", workerThreads, completionThreads);
            ThreadPool.SetMinThreads(0, 0);

            // start ActorSystem
            _clusterSystem = ActorSystem.Create("ClusterSys", actorSystemSetup);

            DebugConfigurator("akka.actor.default-dispatcher", _clusterSystem);
            DebugConfigurator("akka.actor.internal-dispatcher", _clusterSystem);
            DebugConfigurator("akka.remote.default-remote-dispatcher", _clusterSystem);
            DebugConfigurator("akka.remote.backoff-remote-dispatcher", _clusterSystem);

            // instantiate actors
            BenchmarkHostRouter = _clusterSystem.ActorOf(Props.Empty.WithRouter(FromConfig.Instance), "host-router");

            BenchmarkCoordinatorManager = _clusterSystem.ActorOf(ClusterSingletonManager.Props(
                                                                     singletonProps: Props.Create(() => new BenchmarkCoordinator(2, 6, BenchmarkHostRouter)),
                                                                     terminationMessage: PoisonPill.Instance,
                                                                     settings: ClusterSingletonManagerSettings.Create(_clusterSystem)), "coordinator");

            BenchmarkCoordinator = _clusterSystem.ActorOf(ClusterSingletonProxy.Props(
                                                              singletonManagerPath: "/user/coordinator",
                                                              settings: ClusterSingletonProxySettings.Create(_clusterSystem)), "coordinator-proxy");

            BenchmarkHost = _clusterSystem.ActorOf(Props.Create(() => new BenchmarkHost(BenchmarkCoordinator)), "host");

            Akka.Cluster.Cluster.Get(_clusterSystem).RegisterOnMemberRemoved(() => {
                _lifetime.StopApplication(); // when the ActorSystem terminates, terminate the process
            });

            return(Task.CompletedTask);
        }