示例#1
0
        public static void Main(string[] args)
        {
            var system = ActorSystem.Create("HelloWorld");

            var actor = system.ActorOf(MyActor.Props());

            Console.WriteLine($"Actor Path: [{actor.Path}]");

            var actor2 = system.ActorSelection(actor.Path);

            var inbox = Inbox.Create(system);

            inbox.Send(actor, new ToWhom("小明"));

            var resp = (Response)inbox.ReceiveAsync(TimeSpan.FromSeconds(5.0)).Result;

            Console.WriteLine($"receive message: {resp.Message}");

            var resp2 = (Response)actor.Ask(new ToWhom("小華"), TimeSpan.FromSeconds(5.0)).Result;

            Console.WriteLine($"receive message: {resp2.Message}");

            actor.Tell(new ToWhom("小黃"), inbox.Receiver);

            var resp3 = (Response)inbox.ReceiveAsync(TimeSpan.FromMinutes(5.0)).Result;

            Console.WriteLine($"receive message: {resp3.Message}");

            Console.ReadLine();
            Console.WriteLine("End!!");
        }
示例#2
0
        public async Task <IWaitResult> Start(TimeSpan?timeout = null)
        {
            if (!_allExpectedMessages.IsEmpty)
            {
                throw new WaiterIsFinishedException();
            }

            using (var inbox = Inbox.Create(_system))
            {
                foreach (var type in ConditionBuilder.MessageFilters.Keys)
                {
                    _subscriber.Subscribe(type, inbox.Receiver);
                }

                var finalTimeout = timeout ?? _defaultTimeout;

                await WaitForMessages(inbox, finalTimeout).TimeoutAfter(finalTimeout);

                foreach (var type in ConditionBuilder.MessageFilters.Keys)
                {
                    _subscriber.Unsubscribe(inbox.Receiver, type);
                }

                return(new WaitResult(_allExpectedMessages));
            }
        }
        public async Task Execute(ICommand command, IMessageMetadata metadata = null, CommandConfirmationMode confirmationMode = CommandConfirmationMode.Projected)
        {
            var envelopedCommand = new MessageMetadataEnvelop(command, metadata ?? CreateEmptyCommandMetadata(command));

            if (confirmationMode == CommandConfirmationMode.None)
            {
                _commandExecutorActor.Tell(envelopedCommand);
                return;
            }

            var inbox = Inbox.Create(_system);

            _commandExecutorActor.Tell(envelopedCommand, inbox.Receiver);

            var msg = await inbox.ReceiveAsync(_defaultTimeout);

            if (CheckMessage(confirmationMode, msg))
            {
                return;
            }

            msg = await inbox.ReceiveAsync(_defaultTimeout);

            if (CheckMessage(confirmationMode, msg))
            {
                return;
            }

            throw new TimeoutException("Command execution took to long");
        }
示例#4
0
 public void EnsureStoped(IActorRef actor)
 {
     using Inbox inbox = Inbox.Create(ActorSystem);
     inbox.Watch(actor);
     ActorSystem.Stop(actor);
     inbox.Receive(TimeSpan.FromMinutes(5));
 }
示例#5
0
        public PeaResult Start(PeaSettings settings, IEvaluationInitData initData)
        {
            var       inbox  = Inbox.Create(System);
            PeaResult result = null;

            try
            {
                inbox.Send(SystemActor, new CreateSystem(settings));
                var response = inbox.Receive(TimeSpan.FromSeconds(30));
                if (response is CreatedSuccessfully)
                {
                    inbox.Send(SystemActor, new InitEvaluator(initData));
                    result = (PeaResult)inbox.Receive(TimeSpan.FromMinutes(30));
                }
            }
            catch (Exception e)
            {
                result = new PeaResult(new List <string>()
                {
                    e.ToString()
                }, new List <IEntity>());
            }


            //var response = await SystemActor.Ask(new CreateSystem(settings));

            //if (response is CreatedSuccessfully)
            //{
            //result = await SystemActor.Ask(new InitEvaluator(initData));
            //}

            return(result);
        }
示例#6
0
        public void Publish_to_stream()
        {
            var pooledWorkers = Sys.ActorOf(Props.Create <Worker>()
                                            .WithRouter(
                                                new ConsistentHashingPool(4, m => (m as DoWorkMessage)?.Id)), "PooledWorker");

            Sys.EventStream.Subscribe(pooledWorkers, typeof(DoWorkMessage));

            var inbox = Inbox.Create(Sys);

            Sys.EventStream.Subscribe(inbox.Receiver, typeof(WorkDoneMessage));
            int totalCount = 10;

            while (--totalCount > 0)
            {
                foreach (var m in Enumerable.Range(0, 100).Select(i => new DoWorkMessage(Guid.NewGuid())))
                {
                    Sys.EventStream.Publish(m);
                    var msg = (WorkDoneMessage)inbox.Receive();
                    Assert.AreEqual(m.Id, msg.Id);
                    Console.WriteLine($"work {m.Id} done by {msg.Executor}");
                }

                Thread.Sleep(TimeSpan.FromSeconds(30));
            }

            Console.WriteLine("received all messages");
        }
示例#7
0
文件: NeoSystem.cs 项目: txhsl/neo
        public void EnsureStoped(IActorRef actor)
        {
            Inbox inbox = Inbox.Create(ActorSystem);

            inbox.Watch(actor);
            ActorSystem.Stop(actor);
            inbox.Receive(Timeout.InfiniteTimeSpan);
        }
示例#8
0
        /// <summary>
        /// Create new instance of pbx proxy
        /// </summary>
        /// <returns>ActorPbxProxy</returns>
        public ActorPbxProxy GetNewActorPbxProxy()
        {
            //Esto lo hago para reemplazar el método GetActorPbxProxy()
            //que antes llamaba desde el program.cs para inciar solo un callmanager
            Inbox inboxPbxProxy = Inbox.Create(systemq);

            actorPbxProxy = new ActorPbxProxy(inboxPbxProxy, actorMsgRouter);
            return(actorPbxProxy);
        }
示例#9
0
        /// <summary>
        /// Prepare Simulation Environment
        /// </summary>
        /// <param name="debug">Enables AKKA-Global message Debugging</param>
        public Simulation(SimulationConfig simConfig)
        {
            Config config = (simConfig.Debug) ? ConfigurationFactory.ParseString(GetConfiguration())
                            /* else */ : ConfigurationFactory.Load();

            ActorSystem       = ActorSystem.Create(SimulationContextName, config);
            simConfig.Inbox   = Inbox.Create(ActorSystem);
            SimulationContext = ActorSystem.ActorOf(Props.Create(() => new SimulationContext(simConfig)), SimulationContextName);
        }
        public static ActorPaths CreateActorPaths(TestKit testKit, IActorRef simContext)
        {
            var simSystem  = testKit.CreateTestProbe();
            var inbox      = Inbox.Create(system: testKit.Sys);
            var agentPaths = new ActorPaths(simulationContext: simContext, systemMailBox: inbox.Receiver);

            agentPaths.SetSupervisorAgent(systemAgent: simSystem);
            agentPaths.Guardians.Add(GuardianType.Contract, testKit.CreateTestProbe());
            agentPaths.Guardians.Add(GuardianType.Dispo, testKit.CreateTestProbe());
            agentPaths.Guardians.Add(GuardianType.Production, testKit.CreateTestProbe());
            return(agentPaths);
        }
        private async Task TerminateActor(IActorRef persistActor)
        {
            var inbox = Inbox.Create(_system);

            inbox.Watch(persistActor);
            persistActor.Tell(PoisonPill.Instance);
            var terminated = await inbox.ReceiveAsync();

            if (!(terminated is Terminated))
            {
                throw new InvalidOperationException();
            }
        }
示例#12
0
 public void Run(NameValueCollection appSettings)
 {
     if (IsRunning)
     {
         return;
     }
     IsRunning     = true;
     Report.Prefix = appSettings["TargetPrefix"];
     _actorSystem  = new ConnectorActors("PI2MV", appSettings, _eventLog);
     _itemSense    = new ItemSenseProxy(appSettings);
     _inbox        = Inbox.Create(_actorSystem.System);
     _actorSystem.ReportZoneMap(_itemSense.GetZoneMap(appSettings["TargetZoneMap"]));
     _itemSense.ConsumeQueue(new AmqpRegistrationParams(), _actorSystem.ProcessAmqp());
     _actorSystem.StartReconciliation(fromTime => _itemSense.GetRecentItems(fromTime));
 }
示例#13
0
        private static async Task ShutDownHubActor(GridDomainNode node, string id, IActorRef aggregateActor, IActorRef aggregateHubActor, TimeSpan?timeout = null)
        {
            using (var inbox = Inbox.Create(node.System))
            {
                inbox.Watch(aggregateActor);
                aggregateHubActor.Tell(new ShutdownChild(id));

                var msg = await inbox.ReceiveAsync(timeout ?? node.DefaultTimeout);

                if (!(msg is Terminated))
                {
                    throw new UnexpectedMessageExpection($"Expected {typeof(Terminated)} but got {msg}");
                }
            }
        }
示例#14
0
        /// <summary>
        ///		Quick test of actor usage.
        /// </summary>
        public static void ActorTest()
        {
            using (ActorSystem actorSystem = ActorSystem.Create("TaskRunner"))
            {
                IActorRef controller = actorSystem.ActorOf <TaskController>("TaskController");

                const int taskCount = 20;

                Log.Verbose("{ActorName}: Calling controller to run {TaskCount} tasks...", nameof(Program), taskCount);
                for (int taskId = 1; taskId <= taskCount; taskId++)
                {
                    controller.Tell(
                        new RunTask("do something #" + taskId)
                        );
                }

                Log.Verbose(
                    "{ActorName}: Stopping controller...",
                    nameof(Program)
                    );

                controller.Tell(Shutdown.Instance);

                // Wait for task controller to observe the completion of all outstanding task.
                using (Inbox inbox = Inbox.Create(actorSystem))
                {
                    while (true)
                    {
                        inbox.Send(controller, GetOutstandingTaskCount.Instance);
                        OutstandingTaskCount outstandingTaskCount = (OutstandingTaskCount)inbox.ReceiveWhere(
                            message => message is OutstandingTaskCount
                            );

                        if (outstandingTaskCount.Count == 0)
                        {
                            break;
                        }

                        Thread.Sleep(
                            TimeSpan.FromMilliseconds(500)
                            );
                    }
                }

                Log.Verbose("{ActorName}: Done.", nameof(Program));
            }
        }
示例#15
0
        /// <summary>
        /// Prepare Simulation Environment
        /// </summary>
        /// <param name="simConfig">Several Simulation Configurations</param>
        public Simulation(SimulationConfig simConfig)
        {
            Config config = (simConfig.DebugAkka) ? ConfigurationFactory.ParseString(GetConfiguration(NLog.LogLevel.Debug))
                            /* else */ : ConfigurationFactory.ParseString(GetConfiguration(NLog.LogLevel.Info));

            ActorSystem = ActorSystem.Create(SimulationContextName, config);

            //
            // ********* Not Ready Yet ******************* ///
            //
            // if(simConfig.AddApplicationInsights)
            // {
            //    var monitor = new ActorAppInsightsMonitor(SimulationContextName);
            //    var monitorExtension = ActorMonitoringExtension.RegisterMonitor(ActorSystem, monitor);
            // }

            simConfig.Inbox   = Inbox.Create(ActorSystem);
            SimulationContext = ActorSystem.ActorOf(Props.Create(() => new SimulationContext(simConfig)), SimulationContextName);
        }
示例#16
0
        public async Task <IWaitResults> Start(TimeSpan?timeout = null)
        {
            using (var inbox = Inbox.Create(_system))
            {
                foreach (var type in _messageTypesToSubscribe)
                {
                    _subscriber.Subscribe(type, inbox.Receiver);
                }

                var finalTimeout = timeout ?? _defaultTimeout;

                await WaitForMessages(inbox, finalTimeout)
                .TimeoutAfter(finalTimeout);

                foreach (var type in _messageTypesToSubscribe)
                {
                    _subscriber.Unsubscribe(inbox.Receiver, type);
                }

                return(new WaitResults(_allExpectedMessages));
            }
        }
示例#17
0
        static void InboxDemo()
        {
            var system = ActorSystem.Create("mysystem");
            var target = system.ActorOf(Props.Create <Worker>());
            var inbox  = Inbox.Create(system);

            inbox.Send(target, "hello");

            try
            {
                var result = inbox.Receive(TimeSpan.FromSeconds(1)).Equals("world");
                Console.WriteLine($"Inbox.Receive={result}");
            }
            catch (TimeoutException tExc)
            {
                Console.WriteLine($"TimeoutException:{tExc.Message}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"总异常:{e.Message}");
            }
        }
示例#18
0
        static void Main(string[] args)
        {
            var system = ActorSystem.Create("EventSourcing");

            var store   = system.ActorOf <CartStore>("store");
            var gateway = system.ActorOf(Props.Create(() => new CartsGateway(store)), "carts");
            //var logger = system.ActorOf<ConsoleLogger>("logger");

            //system.EventStream.Subscribe(logger, typeof(CartInitializedEvent));
            //system.EventStream.Subscribe(logger, typeof(ItemAddedEvent));
            //system.EventStream.Subscribe(logger, typeof(ItemRemovedEvent));

            var inbox = Inbox.Create(system);

            inbox.Send(gateway, new InitializeCartCommand(Guid.NewGuid(), "Cart1", "melkio"));
            inbox.Send(gateway, new AddItemCommand(Guid.NewGuid(), "Cart1", "item1", 5));
            inbox.Send(gateway, new AddItemCommand(Guid.NewGuid(), "Cart1", "item2", 1));
            inbox.Send(gateway, new RemoveItemCommand(Guid.NewGuid(), "Cart1", "item1", 3));
            inbox.Send(gateway, new RemoveItemCommand(Guid.NewGuid(), "Cart1", "item2", 2));

            var stop = false;

            do
            {
                try
                {
                    var response = inbox.Receive(TimeSpan.FromSeconds(1));
                    Console.WriteLine(response.GetType());
                }
                catch (Exception)
                {
                    stop = true;
                }
            } while (!stop);

            Console.ReadLine();
        }
示例#19
0
        /// <summary>
        /// Esta clase inicia el sistema de actores, crea un router de mensajes y una instancia del proxy para la pbx
        /// </summary>
        public QActorSystem(SystemConfiguration systemConfig)
        {
            this.systemConfig = systemConfig;

            //conf sanples
            //https://github.com/akkadotnet/akka.net/blob/v1.3/src/core/Akka/Configuration/Pigeon.conf
            //Conf Dispatcher
            //https://blog.knoldus.com/2016/01/15/sample-akka-dispatcher-configuration/
            //loggers = [""Akka.Logger.Serilog.SerilogLogger, Akka.Logger.Serilog""]
            var config = ConfigurationFactory.ParseString(@"
                akka {
                        log-config-on-start = on
                        stdout-loglevel = DEBUG
                        loglevel = DEBUG
                        loggers = [""Akka.Logger.Serilog.SerilogLogger, Akka.Logger.Serilog""]
                
                    actor {
                            provider = ""Akka.Remote.RemoteActorRefProvider, Akka.Remote""
                            debug {
                                    receive = on
                                    autoreceive = on
                                    lifecycle = on
                                    event-stream = on
                                    unhandled = on
                                    }
                            my-pinned-dispatcher {
                                type = ""PinnedDispatcher""
                                executor = ""fork-join-executor""
                            }
                            inbox {
                                inbox-size=100000
                            }

                        }
                        remote {
                            dot-netty.tcp {
                                port = 8081
                                hostname = 0.0.0.0
                                public-hostname = localhost
                            }
                        }
                            
                    }");

            //Creo logger para actores, life cycle, y demas del sistema de actores.
            Serilog.Core.Logger logger = new LoggerConfiguration()
                                         .WriteTo.ColoredConsole()
                                         .MinimumLevel.Debug()
                                         .CreateLogger();
            Serilog.Log.Logger = logger; //Esto es necesario para que akka utilice el serilog
            SerilogLogger serifake;

            Akka.Remote.RemoteActorRef fackeRef;
            systemq = ActorSystem.Create("clover-q", config);
            //systemq.Log.Info("Sistema de acotores iniciado.");

            Inbox inboxPbxProxy   = Inbox.Create(systemq);
            Inbox inboxStateProxy = Inbox.Create(systemq);
            Inbox inboxLoginProxy = Inbox.Create(systemq);



            //Este actor se encarga de acceder al sistema de persistencia (DB)
            actorDataAccess = systemq.ActorOf(Props.Create(() => new ActorDataAccess()).WithDispatcher("akka.actor.my-pinned-dispatcher"), "ActorDataAccess");

            //Este actor se encarga de generar el queuelog
            actorQueueLog = systemq.ActorOf(Props.Create(() => new ActorQueueLog()).WithDispatcher("akka.actor.my-pinned-dispatcher"), "ActorQueueLog");

            //Creo el calldistributor, este actor es el que al recibir una llamada nueva intenta rutearla a un agente libre,
            //tambien recibe mensajes del actorStateProxy para mantener el estado de los dispositivos de los agentes
            actorCallDistributor = systemq.ActorOf(Props.Create(() => new ActorCallDistributor(actorDataAccess, actorQueueLog)).WithDispatcher("akka.actor.my-pinned-dispatcher"), "CallDistributor");

            //Este actor se encarga de recibir mensajes desde la API REST con Nancy
            actorRestApiGW = systemq.ActorOf(Props.Create(() => new ActorRestApiGW(actorCallDistributor)).WithDispatcher("akka.actor.my-pinned-dispatcher"), "ActorRestApiGW");


            actorMsgRouter          = systemq.ActorOf(Props.Create(() => new ActorMsgRouter(actorCallDistributor)).WithDispatcher("akka.actor.my-pinned-dispatcher"), "MsgRouter");
            actorMemberLoginService = systemq.ActorOf(Props.Create(() => new ActorMemberLoginService(actorCallDistributor, actorDataAccess, inboxStateProxy.Receiver)).WithDispatcher("akka.actor.my-pinned-dispatcher"), "MemberLoginService");

            actorPbxProxy   = new ActorPbxProxy(inboxPbxProxy, actorMsgRouter);
            actorStateProxy = new ActorStateProxy(inboxStateProxy, actorCallDistributor);
            actorLoginProxy = new ActorLoginProxy(inboxLoginProxy, actorMemberLoginService);
        }
示例#20
0
 public InboxSpec()
     : base("akka.actor.inbox.inbox-size=1000")  //Default is 1000 but just to make sure these tests don't fail we set it
 {
     _inbox = Inbox.Create(Sys);
 }
示例#21
0
 public InboxSpec()
 {
     _inbox = Inbox.Create(sys);
 }