Exemplo n.º 1
0
        private static Func <Exception, bool> RetryInterval(ExceptionHandler isHandled, IEnumerable <TimeSpan> intervals, Action <Exception, TimeSpan> retryAction)
        {
            IEnumerator <TimeSpan> enumerator = intervals.GetEnumerator();

            return(x =>
            {
                if (!isHandled(x))
                {
                    return false;
                }

                if (!enumerator.MoveNext())
                {
                    return false;
                }

                TimeSpan interval = enumerator.Current;

                retryAction(x, interval);

                ThreadUtil.Sleep(interval);

                return true;
            });
        }
Exemplo n.º 2
0
        public void Run(IServiceBus bus, IEndpoint sendTo, IEnumerable <IServiceBus> instances, int iterations,
                        Func <Guid, TRequest> generateRequest)
        {
            using (bus.SubscribeInstance(this).Disposable())
            {
                instances.Each(x => x.ShouldHaveRemoteSubscriptionFor <TResponse>());

                for (int i = 0; i < iterations; i++)
                {
                    var commandInstance = new CommandInstance();
                    lock (_commands)
                        _commands.Add(commandInstance.Id, commandInstance);

                    TRequest command = generateRequest(commandInstance.Id);

                    ThreadUtil.Sleep(5.Milliseconds());

                    sendTo.Send(command, x => { x.SendResponseTo(bus.Endpoint); });
                }

                _received.WaitOne(20.Seconds(), true);
                while (_received.WaitOne(8.Seconds(), true))
                {
                }
            }

            DisplayResults();
        }
Exemplo n.º 3
0
        public void Run(IServiceBus bus, int iterations, Func <Guid, TRequest> generateRequest)
        {
            using (bus.Subscribe(this).Disposable())
            {
                ThreadUtil.Sleep(2.Seconds());

                for (int i = 0; i < iterations; i++)
                {
                    var commandInstance = new CommandInstance();
                    lock (_commands)
                        _commands.Add(commandInstance.Id, commandInstance);

                    var command = generateRequest(commandInstance.Id);

                    ThreadUtil.Sleep(5.Milliseconds());

                    bus.Publish(command, x =>
                    {
                        x.SendResponseTo(bus.Endpoint);

                        x.IfNoSubscribers <FirstCommand>(message => { throw new InvalidOperationException("No subscriptions were found (timing error?)"); });
                    });
                }

                while (_received.WaitOne(5.Seconds(), true))
                {
                }
            }

            DisplayResults();
        }
Exemplo n.º 4
0
        public void Each_subscriber_should_only_receive_once()
        {
            ThreadUtil.Sleep(4.Seconds());

            IEnumerable <IGrouping <int, int> > byReceiver = receivedMessages.GroupBy(r => r);

            byReceiver.All(g => g.Count() == 1).ShouldBeTrue();
        }
Exemplo n.º 5
0
        void FirstCommandConsumer(IConsumeContext <FirstCommand> context, FirstCommand message)
        {
            ThreadUtil.Sleep(10.Milliseconds());

            var response = new FirstResponse(message.CorrelationId);

            context.Respond(response);
        }
        public void Should_not_remove_any_existing_subscriptions()
        {
            RemoteBus.Subscribe <A>(x => { });
            RemoteBus.Dispose();

            ThreadUtil.Sleep(2.Seconds());

            LocalBus.ShouldHaveSubscriptionFor <A>();
        }
Exemplo n.º 7
0
 private void QueryService(QueryContent message)
 {
     ThreadUtil.Sleep((message.Id * 100).Milliseconds());
     message.ResponseChannel.Send(new MyContent
     {
         Title  = "Content Id " + message.Id,
         Detail = "Details of Content Id " + message.Id + " created at " + DateTime.Now.ToLongTimeString(),
     });
 }
        Action <FirstCommand> FirstCommandConsumer(FirstCommand message)
        {
            return(command =>
            {
                ThreadUtil.Sleep(10.Milliseconds());

                var response = new FirstResponse(command.CorrelationId);

                LocalBus.Context().Respond(response);
            });
        }
Exemplo n.º 9
0
        private static Action <FirstCommand> FirstCommandConsumer(FirstCommand message)
        {
            return(command =>
            {
                ThreadUtil.Sleep(10.Milliseconds());

                var response = new FirstResponse(command.CorrelationId);

                CurrentMessage.Respond(response);
            });
        }
Exemplo n.º 10
0
        public void Should_properly_serialize_a_response()
        {
            var actor = AnonymousActor.New(inbox =>
            {
                _channel.Respond(new Test
                {
                    Name = "Magic"
                }, "21");
            });

            ThreadUtil.Sleep(1.Seconds());
        }
Exemplo n.º 11
0
        /// <summary> 检测登录二维码扫描状态 </summary>
        /// <param name="uid"></param>
        private WxLoginScanResult executeLoginScanHttpTask(string uid)
        {
            try
            {
                string tip = "1";
                while (true)
                {
                    HttpTask ht = syncCreateHttpTask(WxHtpUtil.GetLoginScanParams(uid, tip));
                    if (ht == null)
                    {
                        return(null);
                    }

                    WxLoginScanResult result = WxRespUtil.ParseLoginScanResp(ht.ExecuteString());
#if Debug
                    Console.WriteLine("wx login scan result =" + (result == null ? "null" : result.Code.ToString()));
#endif
                    if (result == null)
                    {
                    }
                    else if (result.Code == WxResultCode.LOGIN_SCAN_SUCCESS)//201
                    {
                        //已扫描,未登录,这里可以获取头像
                        tip = "0";
                    }
                    else if (result.Code == WxResultCode.LOGIN_SCAN_LOGIN)//200
                    {
                        //点击登录
                        return(result);
                    }
                    else if (result.Code == WxResultCode.LOGIN_SCAN_TIMEOUT)//408
                    {
                        //微信端返的连接超时,继续连接
                    }
                    else if (result.Code == WxResultCode.LOGIN_SCAN_EXPIRED)//400
                    {
                        //二维码过期
                        return(result);
                    }

                    ThreadUtil.Sleep(500);

                    if (!syncCheckLoginingState())
                    {
                        return(null);
                    }
                }
            }
            catch { }

            return(null);
        }
Exemplo n.º 12
0
        public void DoSomething(object state)
        {
            var transaction = state as DependentTransaction;

            Magnum.Guard.AgainstNull(transaction, "transaction");
            using (transaction)
            {
                ThreadUtil.Sleep(100.Milliseconds());

                transaction.Rollback(new InvalidOperationException("System screwed up"));
                //	transaction.Complete();
            }
        }
Exemplo n.º 13
0
        public void Should_remove_any_previous_subscriptions()
        {
            RemoteBus.SubscribeHandler <A>(x => { });
            RemoteBus.ShouldHaveSubscriptionFor <A>();
            LocalBus.ShouldHaveRemoteSubscriptionFor <A>();

            RemoteBus.Dispose();

            ThreadUtil.Sleep(2.Seconds());

            SetupRemoteBus();

            LocalBus.ShouldNotHaveSubscriptionFor <A>();
        }
        public void Consume(SendOrderDetailsRequest request)
        {
            // simulate a call to the external service

            ThreadUtil.Sleep(1.Seconds());

            var details = new OrderDetailsResponse
            {
                OrderId    = request.OrderId,
                CustomerId = request.CustomerId,
                Created    = (-1).Days().FromUtcNow(),
                Status     = OrderStatus.InProcess,
            };

            CurrentMessage.Respond(details, x => x.ExpiresAt(5.Minutes().FromNow()));
        }
Exemplo n.º 15
0
        void AddEventForwarders(ConnectionConfigurator x)
        {
            // These are needed to ensure that events are updated in the shelf state machine
            // as well as the service coordinator state machine. To handle this, the servicecontroller
            // is given the shelf channel as the reporting channel for events, and the shelf forwards
            // the events to the service coordinator

            x.AddConsumerOf <ServiceEvent>()
            .UsingConsumer(OnServiceEvent)
            .HandleOnCallingThread();

            x.AddConsumerOf <ServiceCreated>()
            .UsingConsumer(m => _controllerChannel.Send(m))
            .HandleOnFiber(_fiber);
            x.AddConsumerOf <ServiceFolderChanged>()
            .UsingConsumer(m => _controllerChannel.Send(m))
            .HandleOnFiber(_fiber);
            x.AddConsumerOf <ServiceRunning>()
            .UsingConsumer(m => _controllerChannel.Send(m))
            .HandleOnFiber(_fiber);
            x.AddConsumerOf <ServiceStopped>()
            .UsingConsumer(m => _controllerChannel.Send(m))
            .HandleOnFiber(_fiber);
            x.AddConsumerOf <ServicePaused>()
            .UsingConsumer(m => _controllerChannel.Send(m))
            .HandleOnFiber(_fiber);
            x.AddConsumerOf <ServiceUnloaded>()
            .UsingConsumer(m =>
            {
                _log.InfoFormat("[{0}] Unloading Shelf and AppDomain", _serviceName);
                _controllerChannel.Send(m);
                ThreadUtil.Sleep(1.Seconds());
                Dispose();
                AppDomain.Unload(AppDomain.CurrentDomain);
            })
            .HandleOnFiber(_fiber);
            x.AddConsumerOf <ServiceFault>()
            .UsingConsumer(m => _controllerChannel.Send(m))
            .HandleOnFiber(_fiber);
        }
Exemplo n.º 16
0
        public void Run()
        {
            Trace.Listeners.Add(new ConsoleTraceListener());

            const string remoteAddress = "rm://234.0.0.7:40001/";

            Guid id = CombGuid.Generate();

            ActorRegistry registry = ActorRegistryFactory.New(x =>
            {
                x.Remote(r => r.ListenTo(remoteAddress));
            });

            ActorRef server = AnonymousActor.New(inbox =>
            {
                inbox.Receive <Response <Hello> >(message =>
                {
                    Console.WriteLine("Hi!");
                    Console.WriteLine("Request ID: " + message.RequestId);
                });
            });


            registry.Register(id, server);

            var actorAddress = new ActorUrn(remoteAddress, id);

            registry.Select(actorAddress, actor =>
            {
                actor.Send <Response <Hello> >(new ResponseImpl <Hello>(new Hello
                {
                    MyNameIs = "Joe",
                }, "27"));
            }, () => {});

            ThreadUtil.Sleep(5.Seconds());

            registry.Shutdown();
        }
Exemplo n.º 17
0
        /// <summary> 执行消息同步循环 </summary>
        /// <param name="wxAccount"></param>
        /// <param name="wxSyncKey"></param>
        private int executeSyncMsgLoop(string host, WxAccount wxAccount, WxSyncKey wxSyncKey)
        {
            //默认账号离线状态
            int code = WxResultCode.ACCOUNT_OFFLINE;

            while (true)
            {
                WxSyncCheckResult syncCheckResult = executeSyncCheckHttpTask(host, wxAccount, wxSyncKey);
#if Debug
                Console.WriteLine("host = " + host + ", synckey reuslt = " + (syncCheckResult == null ? "null" : syncCheckResult.Retcode.ToString()));
#endif
                if (!syncCheckLoginInState())
                {
                    //检测登录状态
                    break;
                }
                else if (syncCheckResult == null)
                {
                    //心跳请求异常
                }
                else if (syncCheckResult.IsStateSuccess)//0
                {
                    //心跳请求成功

                    if (syncCheckResult.Selector != 0)
                    {
                        //有消息需要同步

                        WxSyncMsgResult syncMsgResult = executeSyncMsgHttpTask(host, wxAccount, wxSyncKey);
#if Debug
                        Console.WriteLine("websync reuslt = " + (syncMsgResult == null ? "null" : syncMsgResult.BaseResponse.Ret.ToString()));
#endif

                        if (!syncCheckLoginInState())
                        {
                            //检测登录状态
                            break;
                        }
                        else if (syncMsgResult == null)
                        {
                            //同步消息请求异常
                        }
                        else if (syncMsgResult.IsStateSuccess)
                        {
                            //同步消息请求成功
                            wxSyncKey = syncMsgResult.SyncCheckKey;
                            OnWxTaskReceiveMsgHandler?.Invoke(wxAccount, syncMsgResult);
                        }
                        else
                        {
                            //同步消息请求失败
                            code = syncCheckResult.Retcode;
                            break;
                        }
                    }
                }
                else
                {
                    //心跳请求失败
                    code = syncCheckResult.Retcode;
                    break;
                }


                ThreadUtil.Sleep(1000);
                if (!syncCheckLoginInState())
                {
                    break;
                }
            }

            return(code);
        }