예제 #1
0
        static void Main(string[] args)
        {
            var config = @"
akka {
actor {
        provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster""
    }
remote {
        helios.tcp {
            hostname = ""127.0.0.1"" 
            public-hostname = ""127.0.0.1""
            port = 50000
        }
    }
cluster {
        seed-nodes = [""akka.tcp://[email protected]:50000""]
        roles = [def]
    }
}";

            var actorSystem = ActorSystem.Create("ActorSystem", config);

            ClusterClientReceptionist.Get(actorSystem);

            Console.ReadKey();
        }
예제 #2
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Title           = $"{NamesRegistry.Router}:{Ports.Router}";

            Config config        = AkkaDistributedHelper.GetAkkaSettings();
            string routerAddress = $"{AkkaDistributedHelper.GetFullyQualifiedDomainName()}:{Ports.Router}";

            config = config
                     .WithFallback(string.Format("akka.remote.dot-netty.tcp.hostname = \"{0}\"",
                                                 AkkaDistributedHelper.GetFullyQualifiedDomainName()))
                     .WithFallback(string.Format("akka.remote.dot-netty.tcp.port = {0}", Ports.Router))
                     .WithFallback(string.Format("akka.cluster.roles = [\"{0}\"]", NamesRegistry.Router))
                     .WithFallback(string.Format("akka.cluster.seed-nodes = [\"{1}://App-Cluster@{0}\"]",
                                                 routerAddress, AkkaDistributedHelper.TcpProtocol));

            MyActorSystem = ActorSystem.Create(NamesRegistry.Cluster, config);

            Props props       = Props.Create <RouterActor>(MyActorSystem);
            var   routerActor = MyActorSystem.ActorOf(props, NamesRegistry.Router);

            ClusterClientReceptionist.Get(MyActorSystem).RegisterService(routerActor);
            Console.WriteLine("Router running...");

            // This blocks the current thread from exiting until MyActorSystem is shut down
            // The ConsoleReaderActor will shut down the ActorSystem once it receives an
            // "exit" command from the user
            MyActorSystem.WhenTerminated.Wait();
            Console.WriteLine("Press any key...");
            Console.ReadKey();
        }
예제 #3
0
        public ClusterClientSpecConfig()
        {
            Client = Role("client");
            First  = Role("first");
            Second = Role("second");
            Third  = Role("third");
            Fourth = Role("fourth");

            CommonConfig = ConfigurationFactory.ParseString(@"
                akka.loglevel = DEBUG
                akka.testconductor.query-timeout = 1m # we were having timeouts shutting down nodes with 5s default
                akka.actor.provider = cluster
                akka.remote.log-remote-lifecycle-events = off
                akka.cluster.auto-down-unreachable-after = 0s
                akka.cluster.client.heartbeat-interval = 1s
                akka.cluster.client.acceptable-heartbeat-pause = 3s
                akka.cluster.client.refresh-contacts-interval = 1s
                # number-of-contacts must be >= 4 because we shutdown all but one in the end
                akka.cluster.client.receptionist.number-of-contacts = 4
                akka.cluster.client.receptionist.heartbeat-interval = 10s
                akka.cluster.client.receptionist.acceptable-heartbeat-pause = 10s
                akka.cluster.client.receptionist.failure-detection-interval = 1s
                akka.test.filter-leeway = 10s
            ")
                           .WithFallback(ClusterClientReceptionist.DefaultConfig())
                           .WithFallback(DistributedPubSub.DefaultConfig());

            TestTransport = true;
        }
예제 #4
0
 /// <summary>
 /// Creates a cluster client, that allows to connect to cluster even thou current actor system is not part of it.
 /// </summary>
 static void RunClusterClient(ActorSystem system)
 {
     //NOTE: to properly run cluster client set up actor ref provider for nodes on `provider = "Akka.Remote.RemoteActorRefProvider, Akka.Remote"`
     system.Settings.InjectTopLevelFallback(ClusterClientReceptionist.DefaultConfig());
     var clusterClient = system.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(system)));
     clusterClient.Tell(new ClusterClient.Send("/user/my-service", new Echo("hello from cluster client")));
 }
예제 #5
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(config.GetString("akka.system.actorsystem-name"), config);

            IActorRef fooActor = system.ActorOf(FooActor.Props(), nameof(FooActor));

            // 등록 함수: RegisterService
            // 해제 함수: UnregisterService
            ClusterClientReceptionist.Get(system).RegisterService(fooActor);

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

            Console.ReadLine();
        }
예제 #6
0
        static void Main(string[] args)
        {
            var currDir  = Directory.GetCurrentDirectory();
            var binIndex = currDir.LastIndexOf("bin", StringComparison.InvariantCultureIgnoreCase);
            var path     = binIndex >= 0 ? currDir.Substring(0, binIndex) : currDir;

            var configuration = new ConfigurationBuilder()
                                .SetBasePath(path)
                                .AddCommandLine(args)
                                .AddEnvironmentVariables()
                                .AddJsonFile("appsettings.json")
                                .Build();

            var akkaConfig = GetAkkaConfig(configuration);

            using (var system = ActorSystem.Create("Cluster", akkaConfig))
            {
                var props   = Props.Create(() => new ManagerActor());
                var manager = system.ActorOf(props, "manager");

                var receptionist = ClusterClientReceptionist.Get(system);
                receptionist.RegisterService(manager);

                // manager.Tell(new Get(10000));

                Console.ReadLine();
                CoordinatedShutdown.Get(system).Run(CoordinatedShutdown.ActorSystemTerminateReason.Instance)
                .Wait();
            }
        }
예제 #7
0
        public static ActorSystem Launch()
        {
            var systemName    = string.Empty;
            var ipAddress     = string.Empty;
            var clusterConfig = ConfigurationFactory.ParseString(File.ReadAllText("akka.hocon"));

            var myConfig = clusterConfig.GetConfig("myactorsystem");

            systemName = myConfig.GetString("actorsystem", systemName);


            var remoteConfig = clusterConfig.GetConfig("akka.remote");

            ipAddress = remoteConfig.GetString("dot-netty.tcp.public-hostname") ??
                        "127.0.0.1";     //localhost as a final default

            int port = remoteConfig.GetInt("dot-netty.tcp.port");

            var selfAddress = $"akka.tcp://{systemName}@{ipAddress}:{port}";

            /*
             * Sanity check
             */
            Console.WriteLine($"ActorSystem: {systemName}; IP: {ipAddress}; PORT: {port}");
            Console.WriteLine("Performing pre-boot sanity check. Should be able to parse address [{0}]", selfAddress);
            selfAddress = new Address("akka.tcp", systemName, ipAddress.Trim(), port).ToString();
            Console.WriteLine("Parse successful.");

            var clusterSeeds = Environment.GetEnvironmentVariable("CLUSTER_SEEDS")?.Trim();

            var seeds = clusterConfig.GetStringList("akka.cluster.seed-nodes");

            if (!string.IsNullOrEmpty(clusterSeeds))
            {
                var tempSeeds = clusterSeeds.Trim('[', ']').Split(',');
                if (tempSeeds.Any())
                {
                    seeds = tempSeeds;
                }
            }

            if (!seeds.Contains(selfAddress))
            {
                seeds.Add(selfAddress);
            }

            var injectedClusterConfigString = seeds.Aggregate("akka.cluster.seed-nodes = [", (current, seed) => current + (@"""" + seed + @""", "));

            injectedClusterConfigString += "]";

            var finalConfig = ConfigurationFactory.ParseString(
                string.Format(@"akka.remote.dot-netty.tcp.public-hostname = {0} 
akka.remote.dot-netty.tcp.port = {1}", ipAddress, port))
                              .WithFallback(ConfigurationFactory.ParseString(injectedClusterConfigString))
                              .WithFallback(clusterConfig);

            return(ActorSystem.Create(systemName, finalConfig
                                      .WithFallback(ClusterClientReceptionist.DefaultConfig())
                                      .WithFallback(Akka.Cluster.Tools.PublishSubscribe.DistributedPubSub.DefaultConfig())));
        }
        public void Start()
        {
            var system = ActorSystem.Create(Constants.ActorSystemName, ConfigurationFactory.Load().WithFallback(ClusterSingletonManager.DefaultConfig()));

            system.Settings.InjectTopLevelFallback(ClusterClientReceptionist.DefaultConfig());
            var settings = ClusterClientSettings.Create(system);
            var client   = system.ActorOf(ClusterClient.Props(settings), clientName);

            while (!shouldStop)
            {
                Console.WriteLine("Press key to send message");
                Console.ReadKey();
                client.Ask <ShardEnvelope>(new ClusterClient.Send("/user/sharding/MyActor", new ShardEnvelope(envelopeId, SendMessage)
                {
                    FromClientId = clientId
                }), TimeSpan.FromSeconds(10))
                .ContinueWith(se =>
                {
                    if (se.Status == TaskStatus.Canceled)
                    {
                        Logger.Warn("He ignored me:(");
                    }
                    else
                    {
                        Logger.Info($"Received response with EntityId: {se.Result.EntityId}, Message: {se.Result.Message}, from NodeId: {se.Result.FromNodeId}");
                    }
                });
            }
        }
예제 #9
0
        protected override void PreStart()
        {
            var c = ClusterClientReceptionist.Get(Context.System);

            //c.RegisterService(Self);
            c.RegisterSubscriber(NamesRegistry.ProgressTopic, Self);
        }
예제 #10
0
        static void StartUp(string[] ports)
        {
            var akkaConfig = ConfigurationFactory.ParseString(@"
                akka {
                    extensions = [""Akka.Cluster.Tools.Client.ClusterClientReceptionistExtensionProvider, Akka.Cluster.Tools""]
                    actor {
                        provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster""
                    }
                    remote {
                        log-remote-lifecycle-events = DEBUG
                        dot-netty.tcp {
                            hostname = ""127.0.0.1""
                            port = 0
                        }
                    }
                    cluster {
                        seed-nodes = [
                            ""akka.tcp://[email protected]:2551"",
                        ]
                        auto-down-unreachable-after = 30s
                        roles = [server]
                    }
                }");

            foreach (var port in ports)
            {
                var config = ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.port=" + port)
                             .WithFallback(akkaConfig);

                var system   = ActorSystem.Create("ClusterSystem", config);
                var greeting = system.ActorOf(Props.Create <GreetingActor>(), "greeting");
                ClusterClientReceptionist.Get(system).RegisterService(greeting);
            }
        }
예제 #11
0
 private void Join(RoleName from, RoleName to)
 {
     RunOn(() =>
     {
         Cluster.Join(Node(to).Address);
         ClusterClientReceptionist.Get(Sys);
     }, from);
     EnterBarrier(from.Name + "-joined");
 }
예제 #12
0
        //[MultiNodeFact(Skip = "TODO")]
        public void ClusterClient_should_reestablish_connection_to_another_receptionist_when_server_is_shutdown()
        {
            ClusterClient_should_demonstrate_usage();

            Within(TimeSpan.FromSeconds(30), () =>
            {
                RunOn(() =>
                {
                    var service2 = Sys.ActorOf(Props.Create(() => new TestService(TestActor)), "service2");
                    ClusterClientReceptionist.Get(Sys).RegisterService(service2);
                    AwaitCount(8);
                }, _first, _second, _third, _fourth);
                EnterBarrier("service2-replicated");

                RunOn(() =>
                {
                    var c = Sys.ActorOf(Client.ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(InitialContacts)), "client2");
                    c.Tell(new Client.ClusterClient.Send("/user/service2", "bonjour", localAffinity: true));
                    ExpectMsg("bonjour-ack");
                    var lastSenderAddress = LastSender.Path.Address;

                    var receptionistRoleName = RoleName(lastSenderAddress);
                    if (receptionistRoleName == null)
                    {
                        throw new Exception("Unexpected missing role name: " + lastSenderAddress);
                    }

                    TestConductor.Exit(receptionistRoleName, 0).Wait();
                    _remainingServerRoleNames.Remove(receptionistRoleName);

                    Within(Remaining - TimeSpan.FromSeconds(3), () =>
                    {
                        AwaitAssert(() =>
                        {
                            c.Tell(new Client.ClusterClient.Send("/user/service2", "hi again", localAffinity: true));
                            ExpectMsg("hi again-ack", TimeSpan.FromSeconds(1));
                        });
                    });
                    Sys.Stop(c);
                }, _client);
                EnterBarrier("verified-3");

                ReceiveWhile(TimeSpan.FromSeconds(2), msg =>
                {
                    if (msg.Equals("hi again"))
                    {
                        return(msg);
                    }
                    else
                    {
                        throw new Exception("unexpected message: " + msg);
                    }
                });
                EnterBarrier("after-4");
            });
        }
예제 #13
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);
        }
예제 #14
0
        private static void Main(string[] args)
        {
            var sys = ActorSystem.Create("cluster-sys");

            var addition = sys.ActorOf(Props.Create(() => new AdditionActor()), "addition");

            ClusterClientReceptionist.Get(sys).RegisterService(addition);

            Console.ReadKey();
        }
예제 #15
0
        public void RegisterOnMemberUp()
        {
            Console.WriteLine(cluster.SelfAddress + "上线.....");
            //actorSystem.ActorOf<SubscriberActor>("sub");
            // var pubeventclient= DistributedPubSubService.For(actorSystem);

            var publisher    = this.actorSystem.ActorOf <PublisherActor>("publisher");
            var receptionist = ClusterClientReceptionist.Get(this.actorSystem);

            receptionist.RegisterService(publisher);
        }
 private void ClusterClient_must_bring_second_node_into_cluster()
 {
     Join(_config.Second, _config.First);
     RunOn(() =>
     {
         var service = Sys.ActorOf(EchoActor.Props(this), "testService");
         ClusterClientReceptionist.Get(Sys).RegisterService(service);
         AwaitMembersUp(2);
     }, _config.Second);
     EnterBarrier("second-up");
 }
예제 #17
0
        public void Should_cluster_receptionist_settings_have_default_config()
        {
            ClusterClientReceptionist.Get(Sys);
            var config = Sys.Settings.Config.GetConfig("akka.cluster.client.receptionist");

            Assert.NotNull(config);
            Assert.Equal("receptionist", config.GetString("name"));
            Assert.Equal(string.Empty, config.GetString("role"));
            Assert.Equal(3, config.GetInt("number-of-contacts"));
            Assert.Equal(TimeSpan.FromSeconds(30), config.GetTimeSpan("response-tunnel-receive-timeout"));
            Assert.Equal(string.Empty, config.GetString("use-dispatcher"));
        }
        public void InitializeCluster()
        {
            _lighthouseSystem     = LighthouseHostFactory.LaunchLighthouse(_ipAddress, _port);
            Program.ClusterSystem = _lighthouseSystem;
            Program.ClusterStatus = Program.ClusterSystem.ActorOf(Props.Create(() => new ClusterStatus(_hostControl)),
                                                                  ActorPaths.ClusterStatusActor.Name);
            Program.ClusterHelper = Program.ClusterSystem.ActorOf(Props.Create(() => new ClusterHelper()),
                                                                  ActorPaths.ClusterHelperActor.Name);

            var receptionist = ClusterClientReceptionist.Get(_lighthouseSystem);

            receptionist.RegisterService(_lighthouseSystem.ActorOf(Props.Create <ClusterManager>(), ActorPaths.ClusterManagerActor.Name));
        }
 private void ClusterClient_must_startup_cluster_with_single_node()
 {
     Within(TimeSpan.FromSeconds(30), () =>
     {
         Join(_config.First, _config.First);
         RunOn(() =>
         {
             var service = Sys.ActorOf(EchoActor.Props(this), "testService");
             ClusterClientReceptionist.Get(Sys).RegisterService(service);
             AwaitMembersUp(1);
         }, _config.First);
         EnterBarrier("cluster-started");
     });
 }
예제 #20
0
        static void Main(string[] args)
        {
            var hoconFileName    = $"{Assembly.GetEntryAssembly().GetName().Name}.hocon";
            var currentDirectory = Directory.GetCurrentDirectory();
            var hoconFilePath    = Path.Combine(currentDirectory, hoconFileName);

            var config = ConfigurationFactory.ParseString(File.ReadAllText(hoconFilePath));
            var system = ActorSystem.Create(config.GetString("akka.system.name"), config);

            ClusterClientReceptionist.Get(system).RegisterService();

            Console.ReadLine();
            system.Terminate().Wait();
        }
예제 #21
0
        public void ClusterClient_must_demonstrate_usage()
        {
            var host1 = _config.First;
            var host2 = _config.Second;
            var host3 = _config.Third;

            Within(15.Seconds(), () =>
            {
                //#server
                RunOn(() =>
                {
                    var serviceA = Sys.ActorOf(Props.Create <ClusterClientSpecConfig.Service>(), "serviceA");
                    ClusterClientReceptionist.Get(Sys).RegisterService(serviceA);
                }, host1);

                RunOn(() =>
                {
                    var serviceB = Sys.ActorOf(Props.Create <ClusterClientSpecConfig.Service>(), "serviceB");
                    ClusterClientReceptionist.Get(Sys).RegisterService(serviceB);
                }, host2, host3);
                //#server

                RunOn(() =>
                {
                    AwaitCount(4);
                }, host1, host2, host3, _config.Fourth);
                EnterBarrier("services-replicated");

                //#client
                RunOn(() =>
                {
                    var c = Sys.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(InitialContacts)), "client");
                    c.Tell(new ClusterClient.Send("/user/serviceA", "hello", localAffinity: true));
                    c.Tell(new ClusterClient.SendToAll("/user/serviceB", "hi"));
                }, _config.Client);
                //#client

                RunOn(() =>
                {
                    // note that "hi" was sent to 2 "serviceB"
                    var received = ReceiveN(3);
                    received.ToImmutableHashSet().Should().BeEquivalentTo(ImmutableHashSet.Create("hello", "hi"));
                }, _config.Client);

                // strange, barriers fail without this sleep
                Thread.Sleep(1000);
                EnterBarrier("after-4");
            });
        }
        public void Start()
        {
            Logger.Info("Starting shard");

            var system = ActorSystem.Create(Constants.ActorSystemName, ConfigurationFactory.Load()
                                            .WithFallback(config)
                                            .WithFallback(ClusterSingletonManager.DefaultConfig()));
            var sharding = ClusterSharding.Get(system);

            shardRegion = sharding.Start(
                typeName: nameof(MyActor),
                entityProps: Props.Create(() => new MyActor(nodeId)),
                settings: ClusterShardingSettings.Create(system),
                messageExtractor: new MessageExtractor(Constants.MaxNumberOfNodes * 10)
                );
            ClusterClientReceptionist.Get(system).RegisterService(shardRegion);
        }
예제 #23
0
        public void ClusterClient_must_reestablish_connection_to_receptionist_after_server_restart()
        {
            Within(30.Seconds(), () =>
            {
                RunOn(() =>
                {
                    _remainingServerRoleNames.Count.Should().Be(1);
                    var remainingContacts = _remainingServerRoleNames.Select(r => Node(r) / "system" / "receptionist").ToImmutableHashSet();
                    var c = Sys.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(remainingContacts)), "client4");

                    c.Tell(new ClusterClient.Send("/user/service2", "bonjour4", localAffinity: true));
                    var reply = ExpectMsg <ClusterClientSpecConfig.Reply>(10.Seconds());
                    reply.Msg.Should().Be("bonjour4-ack");
                    reply.Node.Should().Be(remainingContacts.First().Address);

                    // TODO: bug, cannot compare with a logsource
                    var logSource = $"{Sys.AsInstanceOf<ExtendedActorSystem>().Provider.DefaultAddress}/user/client4";

                    EventFilter.Info(start: "Connected to").ExpectOne(() =>
                    {
                        EventFilter.Info(start: "Lost contact").ExpectOne(() =>
                        {
                            // shutdown server
                            TestConductor.Shutdown(_remainingServerRoleNames.First()).Wait();
                        });
                    });

                    c.Tell(new ClusterClient.Send("/user/service2", "shutdown", localAffinity: true));
                    Thread.Sleep(2000); // to ensure that it is sent out before shutting down system
                }, _config.Client);

                RunOn(() =>
                {
                    Sys.WhenTerminated.Wait(20.Seconds());
                    // start new system on same port
                    var port = Cluster.Get(Sys).SelfAddress.Port;
                    var sys2 = ActorSystem.Create(
                        Sys.Name,
                        ConfigurationFactory.ParseString($"akka.remote.dot-netty.tcp.port={port}").WithFallback(Sys.Settings.Config));
                    Cluster.Get(sys2).Join(Cluster.Get(sys2).SelfAddress);
                    var service2 = sys2.ActorOf(Props.Create(() => new ClusterClientSpecConfig.TestService(TestActor)), "service2");
                    ClusterClientReceptionist.Get(sys2).RegisterService(service2);
                    sys2.WhenTerminated.Wait(20.Seconds());
                }, _remainingServerRoleNames.ToArray());
            });
        }
예제 #24
0
        public static void StartUp(string port)
        {
            var section = (AkkaConfigurationSection)ConfigurationManager.GetSection("akka");

            //Override the configuration of the port
            var config =
                ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.port=" + port)
                .WithFallback(section.AkkaConfig);

            //create an Akka system
            var system = ActorSystem.Create("cluster-playground", config);

            //create an actor that handles cluster domain events
            var node = system.ActorOf(Node.MyProps(port), "node");

            ClusterClientReceptionist.Get(system).RegisterService(node);
            system.WhenTerminated.Wait();
        }
예제 #25
0
        //[MultiNodeFact(Skip = "TODO")]
        public void ClusterClient_should_demonstrate_usage()
        {
            ClusterClient_should_communicate_to_any_node_in_cluster();

            Within(TimeSpan.FromSeconds(15), () =>
            {
                RunOn(() =>
                {
                    var serviceA = Sys.ActorOf(Props.Create <Service>(), "serviceA");
                    ClusterClientReceptionist.Get(Sys).RegisterService(serviceA);
                }, _first);

                RunOn(() =>
                {
                    var serviceB = Sys.ActorOf(Props.Create <Service>(), "serviceB");
                    ClusterClientReceptionist.Get(Sys).RegisterService(serviceB);
                }, _second, _third);

                RunOn(() =>
                {
                    AwaitCount(4);
                }, _first, _second, _third, _fourth);

                RunOn(() =>
                {
                    var c = Sys.ActorOf(Client.ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(InitialContacts)), "client");
                    c.Tell(new Client.ClusterClient.Send("/user/serviceA", "hello", localAffinity: true));
                    c.Tell(new Client.ClusterClient.SendToAll("/user/serviceB", "hi"));
                }, _client);

                RunOn(() =>
                {
                    // note that "hi" was sent to 2 "serviceB"
                    var received = ReceiveN(3);
                    Assert.True(received.Contains("hello"));
                    Assert.True(received.Contains("hi"));
                }, _client);

                // strange, barriers fail without this sleep
                Thread.Sleep(1000);
                EnterBarrier("after-3");
            });
        }
        protected override void PreStart()
        {
            base.PreStart();

            _receptionistActor = ClusterClientReceptionist.Get(Context.System).Underlying;

            //
            // 이벤트 등록: SubscribeClusterClients.Instance
            //      -> Receive<ClusterClients>
            //      -> Receive<ClusterClientUp>
            //      -> Receive<ClusterClientUnreachable >
            // 이벤트 제거: UnsubscribeClusterClients.Instance
            //
            //   vs.
            //
            // 명시적 확인 : GetClusterClients.Instance
            //      ->
            _receptionistActor.Tell(SubscribeClusterClients.Instance);
        }
예제 #27
0
        public static Config BoostrapApplication(this Config c, AppBootstrapConfig appConfig)
        {
            var config = c;

            if (appConfig.NeedPersistence)
            {
                var mongoConnectionString = Environment.GetEnvironmentVariable("MONGO_CONNECTION_STR")?.Trim();
                if (string.IsNullOrEmpty(mongoConnectionString))
                {
                    Console.WriteLine("ERROR! MongoDb connection string not provided. Can't start.");
                    throw new ConfigurationException("ERROR! MongoDb connection string not provided. Can't start.");
                }
                else
                {
                    Console.WriteLine("Connecting to MongoDb at {0}", mongoConnectionString);
                }

                config = c.WithFallback(GetMongoHocon(mongoConnectionString));
            }

            config = config
                     .WithFallback(GetOpsConfig())
                     .WithFallback(TradeEventSerializer.Config)
                     .WithFallback(ClusterSharding.DefaultConfig())
                     .WithFallback(DistributedData.DistributedData.DefaultConfig()) // needed for DData sharding
                     .WithFallback(ClusterClientReceptionist.DefaultConfig())
                     .WithFallback(DistributedPubSub.DefaultConfig())
                     .BootstrapFromDocker();


#if PHOBOS
            return(config.BootstrapPhobos(appConfig));
#else
            if (!appConfig.NeedClustering)
            {
                return(ConfigurationFactory.ParseString("akka.actor.provider = remote").WithFallback(config));
            }


            return(config);
#endif
        }
예제 #28
0
        public async Task StartAsync()
        {
            var setup = ActorSystemSetup.Create(
                BootstrapSetup.Create()
                .WithConfig(Util.Config(_port))
                .WithConfigFallback(DistributedPubSub.DefaultConfig())
                .WithConfigFallback(ClusterClientReceptionist.DefaultConfig())
                .WithActorRefProvider(ProviderSelection.Cluster.Instance));

            _actorSystem = ActorSystem.Create(Consts.NodeName, setup);
            var cluster = Akka.Cluster.Cluster.Get(_actorSystem);
            await cluster.JoinSeedNodesAsync(Consts.Seeds);

            _receptionist = ClusterClientReceptionist.Get(_actorSystem);
            foreach (var id in Enumerable.Range(_nodeId * Consts.ActorCount, Consts.ActorCount))
            {
                var actor = _actorSystem.ActorOf(Props.Create(() => new ServiceActor(id)), Util.ActorName(id));
                _receptionist.RegisterService(actor);
            }
        }
예제 #29
0
        public ClusterClientStopSpecConfig()
        {
            Client = Role("client");
            First  = Role("first");
            Second = Role("second");

            CommonConfig = ConfigurationFactory.ParseString(@"
                akka.loglevel = INFO
                akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster""
                akka.remote.log-remote-lifecycle-events = off
                akka.cluster.client {
                  heartbeat-interval = 1s
                  acceptable-heartbeat-pause = 1s
                  reconnect-timeout = 3s
                  receptionist.number-of-contacts = 1
                }
                akka.test.filter-leeway = 10s
            ")
                           .WithFallback(ClusterClientReceptionist.DefaultConfig())
                           .WithFallback(DistributedPubSub.DefaultConfig());
        }
예제 #30
0
        public void ClusterClient_must_startup_cluster()
        {
            Within(30.Seconds(), () =>
            {
                Join(_config.First, _config.First);
                Join(_config.Second, _config.First);

                RunOn(() =>
                {
                    var service = Sys.ActorOf(Props.Create(() => new ClusterClientStopSpecConfig.Service()), "testService");
                    ClusterClientReceptionist.Get(Sys).RegisterService(service);
                }, _config.First);

                RunOn(() =>
                {
                    AwaitCount(1);
                }, _config.First, _config.Second);

                EnterBarrier("cluster-started");
            });
        }