public void ClusterClientSettings_must_throw_exception_on_empty_initial_contacts()
        {
            var clusterClientSettings = ClusterClientSettings.Create(Sys);
            var exception             = Assert.Throws <ArgumentException>(() => clusterClientSettings.WithInitialContacts(ImmutableHashSet <ActorPath> .Empty));

            exception.Message.Should().Be("InitialContacts must be defined");
        }
        public void ClusterClientSettings_must_throw_exception_on_wrong_buffer(int bufferSize)
        {
            var sys       = ActorSystem.Create("test", ConfigurationFactory.ParseString("akka.cluster.client.buffer-size = " + bufferSize));
            var exception = Assert.Throws <ArgumentException>(() => ClusterClientSettings.Create(sys));

            exception.Message.Should().Be("BufferSize must be >= 0 and <= 10000");
        }
Ejemplo n.º 3
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")));
 }
Ejemplo n.º 4
0
        public void ClusterClient_must_report_removal_of_a_receptionist()
        {
            Within(TimeSpan.FromSeconds(30), () =>
            {
                RunOn(() =>
                {
                    var unreachableContact = Node(_config.Client) / "system" / "receptionist";
                    var expectedRoles      =
                        ImmutableHashSet.Create(_config.First, _config.Second, _config.Third, _config.Fourth);
                    var expectedContacts = expectedRoles.Select(x => Node(x) / "system" / "receptionist").ToImmutableHashSet();

                    // We need to slow down things otherwise our receptionists can sometimes tell us
                    // that our unreachableContact is unreachable before we get a chance to
                    // subscribe to events.
                    foreach (var role in expectedRoles)
                    {
                        TestConductor.Blackhole(_config.Client, role, ThrottleTransportAdapter.Direction.Both)
                        .Wait();
                    }

                    var c = Sys.ActorOf(
                        ClusterClient.Props(ClusterClientSettings.Create(Sys)
                                            .WithInitialContacts(expectedContacts.Add(unreachableContact))), "client5");

                    var probe = CreateTestProbe();
                    c.Tell(SubscribeContactPoints.Instance, probe.Ref);

                    foreach (var role in expectedRoles)
                    {
                        TestConductor.PassThrough(_config.Client, role, ThrottleTransportAdapter.Direction.Both)
                        .Wait();
                    }

                    probe.FishForMessage(o => (o is ContactPointRemoved cp && cp.ContactPoint.Equals(unreachableContact)), TimeSpan.FromSeconds(10), "removal");
                }, _config.Client);
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            var initialContacts = ImmutableHashSet <ActorPath> .Empty
                                  .Add(ActorPath.Parse("akka.tcp://Cluster@localhost:12000/system/receptionist"));

            //.Add(ActorPath.Parse("akka.tcp://ClusterClientExample@localhost:12001/user/service"));

            using (var system = ActorSystem.Create("ClusterClient"))
            {
                var clusterClientSettings = ClusterClientSettings.Create(system)
                                            .WithInitialContacts(initialContacts);
                // Creaste the Props used to deploy the cluster client on the local actor system

                var clusterClientProps = ClusterClient.Props(clusterClientSettings);
                //Deploy the cluster client into the local actor system
                //Ovaj dio je prebacen u actora kako bi vidjeli da mozemo iz bilo kojeg actora pristupiti nekom clusteru,
                // a ne samo iz actora stvorenih iz system.ActorOf
                //var clusterClient = system.ActorOf(clusterClientProps, "clusterClient");

                //clusterClient.Tell(new ClusterClient.Send("/user/service", new Msg($"Hello from cluster client")));

                var props = Props.Create(() => new ChatActor(clusterClientProps));
                var actor = system.ActorOf(props);

                Console.ReadLine();
                actor.Tell(new Init());

                Console.ReadLine();
                actor.Tell(new InitPub());

                Console.ReadLine();
            }
        }
Ejemplo n.º 6
0
        protected override void PreStart()
        {
            _clusterClient = Context.ActorOf(ClusterClient.Props(
                                                 ClusterClientSettings.Create(Context.System).WithInitialContacts(Consts.ContactPoints)));

            Timers.StartPeriodicTimer(TimerName, SendPing.Instance, TimeSpan.FromSeconds(1));
        }
        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}");
                    }
                });
            }
        }
Ejemplo n.º 8
0
        private static void InitializeProgressSubscription()
        {
            string receptionistActorPath = string.Format("{3}://App-Cluster@{0}:{1}/system/{2}",
                                                         AkkaDistributedHelper.GetFullyQualifiedDomainName(), Ports.Router, "receptionist", TcpProtocol);
            ImmutableHashSet <ActorPath> initialContacts = ImmutableHashSet.Create(ActorPath.Parse(receptionistActorPath));

            var settings = ClusterClientSettings.Create(MyActorSystem).WithInitialContacts(initialContacts);

            clusterClient = MyActorSystem.ActorOf(ClusterClient.Props(settings), "Client");

            subscriber = MyActorSystem.ActorOf(Props.Create <ProgressSubscriberActor>(), NamesRegistry.ProgressSubscriber);

            Timer progressTimer = new Timer
            {
                Interval = 500
            };

            progressTimer.Enabled  = true;
            progressTimer.Elapsed += (sender, args) =>
            {
                object response = clusterClient.Ask(new ClusterClient.Publish(NamesRegistry.ProgressTopic,
                                                                              new ProgressPublisherActor.ProgressUpdateRequest())).Result;
                subscriber.Tell(response);
            };

            Console.WriteLine($"Created Subscriber for progress updates: {clusterClient.Path} on {MyActorSystem.Name}");
        }
Ejemplo n.º 9
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);

            var cmd = PetabridgeCmd.Get(system);

            cmd.Start();

            //
            // Cluster 접속하기
            //
            system.ActorOf(
                ClusterClient
                .Props(ClusterClientSettings.Create(system)),
                "ClusterClientActor");

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

            Console.ReadLine();
        }
        public void ClusterClientSettings_must_copy_initial_contacts_via_fluent_interface()
        {
            var initialContacts = ImmutableHashSet <ActorPath> .Empty.Add(new RootActorPath(Address.AllSystems) / "user" / "foo");

            var clusterClientSettings = ClusterClientSettings.Create(Sys).WithInitialContacts(initialContacts).WithBufferSize(2000);

            clusterClientSettings.InitialContacts.Should().BeEquivalentTo(initialContacts);
        }
Ejemplo n.º 11
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");
            });
        }
Ejemplo n.º 12
0
        protected override void PreStart()
        {
            _clusterClient = Context.ActorOf(
                ClusterClient
                .Props(ClusterClientSettings.Create(Context.System)),
                "ClusterClientActor");

            _pingTask = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(TimeSpan.FromSeconds(1),
                                                                                  TimeSpan.FromSeconds(1), Self, TryPing.Instance, ActorRefs.NoSender);
        }
        public void ClusterClientSettings_must_have_default_config()
        {
            var clusterClientSettings = ClusterClientSettings.Create(Sys);

            clusterClientSettings.Should().NotBeNull();
            clusterClientSettings.InitialContacts.Should().HaveCount(0);
            clusterClientSettings.EstablishingGetContactsInterval.Should().Be(3.Seconds());
            clusterClientSettings.RefreshContactsInterval.Should().Be(60.Seconds());
            clusterClientSettings.HeartbeatInterval.Should().Be(2.Seconds());
            clusterClientSettings.AcceptableHeartbeatPause.Should().Be(13.Seconds());
            clusterClientSettings.BufferSize.Should().Be(1000);
        }
 private void ClusterClient_must_establish_connection_to_first_node()
 {
     RunOn(() =>
     {
         _clusterClient =
             Sys.ActorOf(
                 ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(InitialContacts)),
                 "client1");
         _clusterClient.Tell(new ClusterClient.Send("/user/testService", "hello", localAffinity: true));
         ExpectMsg <string>().Should().Be("hello");
     }, _config.Client);
     EnterBarrier("established");
 }
Ejemplo n.º 15
0
        //[MultiNodeFact(Skip = "TODO")]
        public void ClusterClient_should_reestablish_connection_to_receptionist_after_partition()
        {
            ClusterClient_should_reestablish_connection_to_another_receptionist_when_server_is_shutdown();

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

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

                    // shutdown all but the one that the client is connected to
                    foreach (var roleName in _remainingServerRoleNames.ToArray())
                    {
                        if (!roleName.Equals(receptionistRoleName))
                        {
                            TestConductor.Exit(roleName, 0).Wait();
                        }
                    }
                    _remainingServerRoleNames = new HashSet <RoleName>(new[] { receptionistRoleName });

                    // network partition between client and server
                    TestConductor.Blackhole(_client, receptionistRoleName, ThrottleTransportAdapter.Direction.Both).Wait();
                    c.Tell(new Client.ClusterClient.Send("/user/service2", "ping", localAffinity: true));
                    // if we would use remote watch the failure detector would trigger and
                    // connection quarantined
                    ExpectNoMsg(TimeSpan.FromSeconds(5));

                    TestConductor.PassThrough(_client, receptionistRoleName, ThrottleTransportAdapter.Direction.Both).Wait();

                    var expectedAddress = Node(receptionistRoleName).Address;
                    AwaitAssert(() =>
                    {
                        c.Tell(new Client.ClusterClient.Send("/user/service2", "bonjour3", localAffinity: true));
                        ExpectMsg("bonjour3-ack", TimeSpan.FromSeconds(1));
                        var lastSenderAddress2 = LastSender.Path.Address;
                        Assert.Equal(expectedAddress, lastSenderAddress2);
                    });
                    Sys.Stop(c);
                }, _client);
                EnterBarrier("after-5");
            });
        }
Ejemplo n.º 16
0
        public ClusterClientSendActor()
        {
            //
            // ClusterClient 액터를 생성한다.
            //
            var c = Context.ActorOf(
                ClusterClient
                .Props(ClusterClientSettings.Create(Context.System)),
                "ClusterClientActor");

            c.Tell(new ClusterClient.Publish("Topic1", "Hello1"));
            c.Tell(new ClusterClient.Publish("Topic1", "Hello2"));
            c.Tell(new ClusterClient.Publish("Topic2", "Hello3"));
        }
Ejemplo n.º 17
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");
            });
        }
Ejemplo n.º 18
0
        public void ClusterClient_must_reestablish_connection_to_receptionist_after_partition()
        {
            Within(30.Seconds(), () =>
            {
                RunOn(() =>
                {
                    var c = Sys.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(InitialContacts)), "client3");
                    c.Tell(new ClusterClient.Send("/user/service2", "bonjour2", localAffinity: true));
                    var reply = ExpectMsg <ClusterClientSpecConfig.Reply>();
                    reply.Msg.Should().Be("bonjour2-ack");

                    RoleName receptionistRoleName = GetRoleName(reply.Node);
                    if (receptionistRoleName == null)
                    {
                        throw new Exception("Unexpected missing role name: " + reply.Node);
                    }

                    // shutdown all but the one that the client is connected to
                    _remainingServerRoleNames.Where(r => !r.Equals(receptionistRoleName)).ForEach(r =>
                    {
                        TestConductor.Exit(r, 0).Wait();
                    });
                    _remainingServerRoleNames = ImmutableHashSet.Create(receptionistRoleName);

                    // network partition between client and server
                    TestConductor.Blackhole(_config.Client, receptionistRoleName, ThrottleTransportAdapter.Direction.Both).Wait();
                    c.Tell(new ClusterClient.Send("/user/service2", "ping", localAffinity: true));
                    // if we would use remote watch the failure detector would trigger and
                    // connection quarantined
                    ExpectNoMsg(5.Seconds());

                    TestConductor.PassThrough(_config.Client, receptionistRoleName, ThrottleTransportAdapter.Direction.Both).Wait();

                    var expectedAddress = GetAddress(receptionistRoleName);
                    AwaitAssert(() =>
                    {
                        var probe = CreateTestProbe();
                        c.Tell(new ClusterClient.Send("/user/service2", "bonjour3", localAffinity: true), probe.Ref);
                        var reply2 = probe.ExpectMsg <ClusterClientSpecConfig.Reply>(1.Seconds());
                        reply2.Msg.Should().Be("bonjour3-ack");
                        reply2.Node.Should().Be(expectedAddress);
                    });
                    Sys.Stop(c);
                }, _config.Client);

                EnterBarrier("after-5");
            });
        }
Ejemplo n.º 19
0
        public ClusterClientSendActor()
        {
            var c = Context.ActorOf(
                ClusterClient
                .Props(ClusterClientSettings.Create(Context.System)),
                "ClusterClientActor");


            ////
            //// 사용자 정의 메시지는 Seed Node에 참조되어야 한다.
            //// TODO: 해결 방법이 없을까?, 메시지를 받는 Node만 참조할 수 없을까?
            ////
            c.Tell(new ClusterClient.Send("/user/FooActor", new CustomWelcome("Send")));
            c.Tell(new ClusterClient.Send("/user/FooActor", new CustomWelcome("Send")));
            c.Tell(new ClusterClient.SendToAll("/user/FooActor", new CustomWelcome("SendToAll")));
        }
Ejemplo n.º 20
0
        public void Should_cluster_client_settings_have_default_config()
        {
            ClusterClientSettings.Create(Sys);
            var config = Sys.Settings.Config.GetConfig("akka.cluster.client");

            Assert.NotNull(config);
            var initialContacts = config.GetStringList("initial-contacts");

            Assert.Equal(0, initialContacts.Count);
            Assert.Equal(TimeSpan.FromSeconds(3), config.GetTimeSpan("establishing-get-contacts-interval"));
            Assert.Equal(TimeSpan.FromSeconds(60), config.GetTimeSpan("refresh-contacts-interval"));
            Assert.Equal(TimeSpan.FromSeconds(2), config.GetTimeSpan("heartbeat-interval"));
            Assert.Equal(TimeSpan.FromSeconds(13), config.GetTimeSpan("acceptable-heartbeat-pause"));
            Assert.Equal(TimeSpan.FromSeconds(3), config.GetTimeSpan("establishing-get-contacts-interval"));
            Assert.Equal(1000, config.GetInt("buffer-size"));
        }
Ejemplo n.º 21
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());
            });
        }
Ejemplo n.º 22
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");
            });
        }
Ejemplo n.º 23
0
        public ClusterClientSendActor()
        {
            //
            // ClusterClient 액터를 생성한다.
            //
            var c = Context.ActorOf(
                ClusterClient
                .Props(ClusterClientSettings.Create(Context.System)),
                // .WithInitialContacts
                "ClusterClientActor");

            //
            // TODO ClusterClientSettings 세부 설정
            //  - WithBufferSize
            //  - WithEstablishingGetContactsInterval
            //  - WithHeartbeatInterval
            //  - WithInitialContacts
            //  - WithReconnectTimeout
            //  - WithRefreshContactsInterval
            //

            //
            // 메시지를 경로가 일치하는 한 액터에게 보낸다.
            // The message will be delivered to one recipient with a matching path, if any such exists
            //
            c.Tell(new ClusterClient.Send("/user/FooActor", "hello-localAffinity", localAffinity: true));
            c.Tell(new ClusterClient.Send("/user/FooActor", "hello-localAffinity", localAffinity: true));

            //
            // Send 기본적으로 경로가 일치하는 액터 중에서 랜덤으로 대상을 선택하여 메시지를 보낸다.
            // random to any other matching entry
            //
            c.Tell(new ClusterClient.Send("/user/FooActor", "hello"));
            c.Tell(new ClusterClient.Send("/user/FooActor", "hello"));
            c.Tell(new ClusterClient.Send("/user/FooActor", "hello"));
            c.Tell(new ClusterClient.Send("/user/FooActor", "hello"));

            //
            // 메시지를 경로가 일치하는 모든 액터에게 보낸다.
            // The message will be delivered to all recipients with a matching path
            //
            c.Tell(new ClusterClient.SendToAll("/user/FooActor", "hi, everybody"));
        }
Ejemplo n.º 24
0
        public void ClusterClient_must_communicate_to_any_node_in_cluster()
        {
            Within(10.Seconds(), () =>
            {
                RunOn(() =>
                {
                    var c = Sys.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(InitialContacts)), "client1");
                    c.Tell(new ClusterClient.Send("/user/testService", "hello", localAffinity: true));
                    ExpectMsg <ClusterClientSpecConfig.Reply>().Msg.Should().Be("hello-ack");
                    Sys.Stop(c);
                }, _config.Client);

                RunOn(() =>
                {
                    ExpectMsg("hello");
                }, _config.Fourth);

                EnterBarrier("after-2");
            });
        }
Ejemplo n.º 25
0
        public ConnectionActor(ClusterClientSettings clusterClientSettings)
        {
            _clusterClientSettings = clusterClientSettings;

            // Receive<JObject>(json => Console.WriteLine(json));
            Receive <GetResult>(result =>
            {
                Console.WriteLine(result.Json);
                Sender.Tell(result);
                Self.Tell(PoisonPill.Instance);
            });
            Receive <GetAllResult>(result =>
            {
                Sender.Tell(result.JArray);
                Self.Tell(PoisonPill.Instance);
            });
            Receive <GetAll>(all => GetAll());
            Receive <Get>(one => GetOne(one));

            Receive <Save>(save => HandleSave(save));
        }
Ejemplo n.º 26
0
        protected override void PreStart()
        {
            _clusterClientActor = Context.ActorOf(
                ClusterClient
                .Props(ClusterClientSettings.Create(Context.System)),
                "ClusterClientActor");

            //
            // 이벤트 등록: SubscribeContactPoints.Instance
            //      -> Receive<ContactPoints>
            //      -> Receive<ContactPointAdded>
            //      -> Receive<ContactPointRemoved>
            // 이벤트 제거: UnsubscribeContactPoints.Instance
            //
            //   vs.
            //
            // 명시적 확인: GetContactPoints.Instance
            //      -> Receive<ContactPoints>
            //
            _clusterClientActor.Tell(SubscribeContactPoints.Instance);
        }
Ejemplo n.º 27
0
        private static void SendToCluster()
        {
            var sys = ActorSystem.Create("sys");

            var client = sys.ActorOf(
                ClusterClient.Props(
                    ClusterClientSettings.Create(sys)
                    .WithInitialContacts(
                        ImmutableHashSet.Create(
                            new[] { ActorPath.Parse("akka.tcp://cluster-sys@localhost:2551/system/receptionist") }))),
                "client");

            var random = new Random(Guid.NewGuid().GetHashCode());

            do
            {
                client.Tell(new ClusterClient.Send("/user/addition", random.Next(10000)));

                Thread.Sleep(1000);
            }while (true);
        }
Ejemplo n.º 28
0
        static void Main(string[] args)
        {
            var config = 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 = [client]
                        client {
                            initial-contacts = [""akka.tcp://[email protected]:2551/system/receptionist""]
                        }
                    }
                }");

            using (var system = ActorSystem.Create("ClusterSystemClient", config))
            {
                system.Settings.InjectTopLevelFallback(ClusterClientReceptionist.DefaultConfig());
                var clusterClient =
                    system.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(system)), "greeting");
                while (true)
                {
                    var message = Console.ReadLine();
                    clusterClient.Tell(new ClusterClient.Send("/user/greeting", new Ping(message)),
                                       system.ActorOf(Props.Create <GreetingActor>()));
                }
            }
        }
Ejemplo n.º 29
0
        public void ClusterClient_must_work_with_ask()
        {
            Within(10.Seconds(), () =>
            {
                RunOn(() =>
                {
                    var c = Sys.ActorOf(ClusterClient.Props(
                                            ClusterClientSettings.Create(Sys).WithInitialContacts(InitialContacts)), "ask-client");
                    var reply = c.Ask <ClusterClientSpecConfig.Reply>(new ClusterClient.Send("/user/testService", "hello-request", localAffinity: true));
                    reply.Wait(Remaining);
                    reply.Result.Msg.Should().Be("hello-request-ack");
                    Sys.Stop(c);
                }, _config.Client);

                RunOn(() =>
                {
                    ExpectMsg("hello-request");
                }, _config.Fourth);

                EnterBarrier("after-3");
            });
        }
Ejemplo n.º 30
0
        //[MultiNodeFact(Skip = "TODO")]
        public void ClusterClient_should_communicate_to_any_node_in_cluster()
        {
            ClusterClient_should_startup_cluster();

            Within(TimeSpan.FromSeconds(10), () =>
            {
                RunOn(() =>
                {
                    var c = Sys.ActorOf(Client.ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(InitialContacts)), "client1");
                    c.Tell(new Client.ClusterClient.Send("/user/testService", "hello", localAffinity: true));
                    ExpectMsg("hello-ack");
                    Sys.Stop(c);
                }, _client);

                RunOn(() =>
                {
                    ExpectMsg("hello");
                }, _fourth);

                EnterBarrier("after-2");
            });
        }