예제 #1
0
        public void SerializationSettingsShouldOverrideHoconSettings()
        {
            var serializationSettings = new SerializationSetup(_ =>
                                                               ImmutableHashSet <SerializerDetails> .Empty
                                                               .Add(SerializerDetails.Create(
                                                                        "test",
                                                                        new TestSerializer(_),
                                                                        ImmutableHashSet <Type> .Empty.Add(typeof(ProgammaticDummy)))));

            var bootstrap = BootstrapSetup.Create().WithConfig(ConfigurationFactory.ParseString(@"
                akka{
                    actor{
                        serialize-messages = on
                        serializers {
                            test = ""Akka.Tests.Serialization.OverridenSerializer, Akka.Test""
                        }
                        serialization-bindings {
                            ""Akka.Tests.Serialization.ProgammaticDummy, Akka.Tests"" = test
                        }
                    }
                }").WithFallback(TestConfigs.DefaultConfig));

            var actorSystemSettings = ActorSystemSetup.Create(serializationSettings, bootstrap);

            var sys2       = ActorSystem.Create("override-test", actorSystemSettings);
            var serializer = sys2.Serialization.FindSerializerFor(new ProgammaticDummy());

            serializer.Should().BeOfType <TestSerializer>();

            sys2.Terminate().Wait();
        }
예제 #2
0
        public void Custom_programmatic_SerializerWithStringManifest_should_work_with_base_class_binding()
        {
            var settings = SerializationSetup.Create(system =>
                                                     ImmutableHashSet <SerializerDetails> .Empty.Add(
                                                         new SerializerDetails(
                                                             alias: "custom",
                                                             serializer: new CustomManifestSerializer(system),
                                                             useFor: ImmutableHashSet <Type> .Empty.Add(typeof(MessageBase))))
                                                     );

            var setup = ActorSystemSetup.Create(settings);

            using (var system = ActorSystem.Create(nameof(CustomSerializerSpec), setup))
            {
                var firstMessage  = new FirstMessage("First message");
                var serialization = system.Serialization;
                var serializer    = (CustomManifestSerializer)serialization.FindSerializerFor(firstMessage);

                var serialized = serializer.ToBinary(firstMessage);
                var manifest   = serializer.Manifest(firstMessage);
                var deserializedFirstMessage = serializer.FromBinary(serialized, manifest);
                manifest.Should().Be(FirstMessage.Manifest);
                deserializedFirstMessage.Should().Be(firstMessage);

                var secondMessage = new SecondMessage("Second message");
                serialized = serializer.ToBinary(secondMessage);
                manifest   = serializer.Manifest(secondMessage);
                var deserializedSecondMessage = serializer.FromBinary(serialized, manifest);
                manifest.Should().Be(SecondMessage.Manifest);
                deserializedSecondMessage.Should().Be(secondMessage);
            }
        }
예제 #3
0
        public void ActorSystemSettingsShouldStoreAndRetrieveSetup()
        {
            var setup  = new DummySetup("Ardbeg");
            var setups = ActorSystemSetup.Create(setup);

            setups.Get <DummySetup>().Should().Be(new Option <DummySetup>(setup));
            setups.Get <DummySetup2>().Should().Be(Option <DummySetup2> .None);
        }
예제 #4
0
        static void Main(string[] args)
        {
            // setup declaring our custom serializer to override the default typeof(object) newtonsoft registration
            var serializationSetup = SerializationSetup.Create(system =>
                                                               ImmutableHashSet <SerializerDetails> .Empty.Add(
                                                                   SerializerDetails.Create("json-custom", new CustomSerializer(system),
                                                                                            ImmutableHashSet <Type> .Empty
                                                                                            // this should make all my messages use CustomSerializer
                                                                                            .Add(typeof(object))
                                                                                            // this is provided to show CustomSerializer gets called,
                                                                                            // i.e, everything appears to be configured correctly
                                                                                            .Add(typeof(World))
                                                                                            )
                                                                   )
                                                               );

            // we just want to force serialization so we don't need to set up remote
            // the goal of the programmatic setup is so apps don't need to register the serializer
            var hocon = ConfigurationFactory.ParseString(@"
akka {
    ""loglevel"": ""DEBUG"",
    ""stdout-loglevel"": ""DEBUG"",
    actor {
        ""serialize-messages"": ""on"",
        ""debug"": {
            ""receive"": ""on"",
            ""lifecycle"": ""on"",
            ""unhandled"": ""on"",
            ""event-stream"": ""on""
        }
    }
}
");
            // I'm not sure why 'serialize-messages' isn't triggering my serializer, not even for
            // my 'World' type. Inspecting system.Serialization._serializerMap reveals the following:
            // [object] = NewtonsoftJsonSerializer
            // [World]  = CustomSerializer
            // [byte[]] = ByteArraySerializer
            // * I thought it might have been dependent on the ordering of ActorSystemSetup.Create(params Setup[] setups)
            //   but I observe the same behavior regardless of the setup ordering.
            var bootstrapSetup = BootstrapSetup.Create().WithConfig(hocon);
            var systemSetup    = ActorSystemSetup.Create(serializationSetup, bootstrapSetup);
            var system         = ActorSystem.Create("system", systemSetup);

            // uncommenting this line and the custom serializer is invoked
            // really bizarre since there is a mapping for typeof(World) but w/out this next line it's not invoked on that type either.
            //system.Serialization.AddSerializationMap(typeof(object), new CustomSerializer(system.Serialization.System));

            var actor    = system.ActorOf(Props.Create(() => new Actor()), "actor");
            var response = actor.Ask <World>(new Hello("world!")).GetAwaiter().GetResult();

            system.Log.Info($"Response: {response.Message}");

            Thread.Sleep(TimeSpan.FromSeconds(20));

            system.Dispose();
        }
예제 #5
0
        public void ActorSystemSettingsShouldBeCreatedWithSetOfSetups()
        {
            var setup1 = new DummySetup("Ardbeg");
            var setup2 = new DummySetup2("Ledaig");
            var setups = ActorSystemSetup.Create(setup1, setup2);

            setups.Get <DummySetup>().HasValue.Should().BeTrue();
            setups.Get <DummySetup2>().HasValue.Should().BeTrue();
            setups.Get <DummySetup3>().HasValue.Should().BeFalse();
        }
예제 #6
0
        private static void Main(string[] args)
        {
            var Bootstrap = BootstrapSetup.Create().WithConfig(ConfigurationFactory.ParseString(@"
akka
{
    actor
    {
        serialize-messages = off
    }
}"));

            var ActorSystemSettings = ActorSystemSetup.Create(SerializationSettings, Bootstrap);
        }
예제 #7
0
        public void ActorSystemSettingsShouldBeAvailableFromExtendedActorSystem()
        {
            ActorSystem system = null;

            try
            {
                var setup = new DummySetup("Eagle Rare");
                system = ActorSystem.Create("name", ActorSystemSetup.Create(setup));

                system.Settings.Setup.Get <DummySetup>().Should().Be(new Option <DummySetup>(setup));
            }
            finally
            {
                system?.Terminate().Wait(TimeSpan.FromSeconds(5));
            }
        }
예제 #8
0
        public ProgrammaticJsonSerializerSetup()
        {
            #region CustomJsonSetup
            var jsonSerializerSetup = NewtonSoftJsonSerializerSetup.Create(
                settings =>
            {
                settings.NullValueHandling          = NullValueHandling.Include;
                settings.PreserveReferencesHandling = PreserveReferencesHandling.None;
                settings.Formatting = Formatting.None;
            });

            var systemSetup = ActorSystemSetup.Create(jsonSerializerSetup);

            var system = ActorSystem.Create("MySystem", systemSetup);
            #endregion

            system.Terminate().Wait();
        }
예제 #9
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);
            }
        }
예제 #10
0
        static void Main(string[] args)
        {
            var logger = new LoggerConfiguration()
                         .WriteTo.File("log.txt", buffered: true, flushToDiskInterval: TimeSpan.FromSeconds(2))
                         .MinimumLevel.Information()
                         .CreateLogger();

            //TestDatabase();

            Serilog.Log.Logger = logger;
            var port = args.Length == 1 ? args[0] : "0";

            var config = hocon
                         .Replace("{{connection_string}}", Environment.GetEnvironmentVariable("CONNECTION_STRING"))
                         .Replace("{{port}}", port)
                         .Replace("{{hostname}}", "172.20.176.1");
            var ConfigBootstrap     = BootstrapSetup.Create().WithConfig(config);
            var ActorSystemSettings = ActorSystemSetup.Create(ConfigBootstrap);

            LotteryActorSystem = ActorSystem.Create(Constants.ActorSystemName, ActorSystemSettings);
            LotteryActorSystem.ActorOf(Props.Create(typeof(SimpleClusterListener)), "clusterListener");
            Props     lotterySupervisorProps = Props.Create <LotterySupervisor>();
            IActorRef lotterySupervisor      = LotteryActorSystem.ActorOf(lotterySupervisorProps, "LotterySupervisor");

            lotterySupervisor.Tell(new BeginPeriodMessage()
            {
                MinTickets = 5, MaxTickets = 10, NumberOfUsers = 20, NumberOfVendors = 150
            });
            Console.WriteLine("Ticket sales have begun, press enter to end period");
            Console.ReadLine();
            lotterySupervisor.Tell(new SupervisorSalesClosedMessage()
            {
            });

            Console.ReadLine();
            LotteryActorSystem.Terminate();

            ////Akka.Logger.Serilog.SerilogLogger
        }
예제 #11
0
        static async Task Main(string[] args)
        {
            var cts = new CancellationTokenSource();

            #region Console shutdown setup
            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                eventArgs.Cancel = true;
                cts.Cancel();
            };

            AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) =>
            {
                cts.Cancel();
            };
            #endregion

            var setup = ActorSystemSetup.Create(
                BootstrapSetup.Create()
                .WithConfig(Util.Config(Consts.PortStart - 1))
                .WithActorRefProvider(ProviderSelection.Remote.Instance));

            var system      = ActorSystem.Create("ClusterClientSystem", setup);
            var clientActor = system.ActorOf(Props.Create(() => new ClientActor()));

            try
            {
                await Task.Delay(Timeout.Infinite, cts.Token);
            }
            catch (TaskCanceledException _)
            {
                // expected
            }

            await system.Terminate();
        }
예제 #12
0
 /// <summary>
 /// Shortcut for creating a new actor system with the specified name and settings.
 /// </summary>
 /// <param name="name">The name of the actor system to create. The name must be uri friendly.
 /// <remarks>Must contain only word characters (i.e. [a-zA-Z0-9] plus non-leading '-'</remarks>
 /// </param>
 /// <param name="setup">The bootstrap setup used to help programmatically initialize the <see cref="ActorSystem"/>.</param>
 /// <returns>A newly created actor system with the given name and configuration.</returns>
 public static ActorSystem Create(string name, BootstrapSetup setup)
 {
     return(Create(name, ActorSystemSetup.Create(setup)));
 }
예제 #13
0
 /// <summary>
 /// Initializes the <see cref="TestState"/> for a new spec.
 /// </summary>
 /// <param name="system">The actor system this test will use. Can be null.</param>
 /// <param name="config">The configuration that <paramref name="system"/> will use if it's null.</param>
 /// <param name="actorSystemName">The name that <paramref name="system"/> will use if it's null.</param>
 /// <param name="testActorName">The name of the test actor. Can be null.</param>
 protected void InitializeTest(ActorSystem system, Config config, string actorSystemName, string testActorName)
 {
     InitializeTest(system, ActorSystemSetup.Create(BootstrapSetup.Create().WithConfig(config)), actorSystemName, testActorName);
 }