Exemple #1
0
        public Consumer(string groupName, ConsumerSetting setting)
        {
            if (groupName == null)
            {
                throw new ArgumentNullException("groupName");
            }
            GroupName = groupName;
            Setting = setting ?? new ConsumerSetting();

            _lockObject = new object();
            _subscriptionTopics = new Dictionary<string, HashSet<string>>();
            _topicQueuesDict = new ConcurrentDictionary<string, IList<MessageQueue>>();
            _pullRequestQueue = new BlockingCollection<PullRequest>(new ConcurrentQueue<PullRequest>());
            _pullRequestDict = new ConcurrentDictionary<string, PullRequest>();
            _messageRetryQueue = new BlockingCollection<ConsumingMessage>(new ConcurrentQueue<ConsumingMessage>());
            _taskFactory = new TaskFactory(new LimitedConcurrencyLevelTaskScheduler(Setting.ConsumeThreadMaxCount));
            _remotingClient = new SocketRemotingClient(Setting.BrokerAddress, Setting.SocketSetting, Setting.LocalAddress);
            _adminRemotingClient = new SocketRemotingClient(Setting.BrokerAdminAddress, Setting.SocketSetting, Setting.LocalAdminAddress);
            _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
            _scheduleService = ObjectContainer.Resolve<IScheduleService>();
            _allocateMessageQueueStragegy = ObjectContainer.Resolve<IAllocateMessageQueueStrategy>();
            _executePullRequestWorker = new Worker("ExecutePullRequest", ExecutePullRequest);
            _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);

            _remotingClient.RegisterConnectionEventListener(new ConnectionEventListener(this));
        }
Exemple #2
0
        static void Main(string[] args)
        {
            ECommonConfiguration
                .Create()
                .UseAutofac()
                .RegisterCommonComponents()
                .UseLog4Net()
                .RegisterUnhandledExceptionHandler();

            _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(typeof(Program).Name);

            var serverIP = ConfigurationManager.AppSettings["ServerAddress"];
            var mode = ConfigurationManager.AppSettings["Mode"];
            var serverAddress = string.IsNullOrEmpty(serverIP) ? SocketUtils.GetLocalIPV4() : IPAddress.Parse(serverIP);
            var parallelThreadCount = int.Parse(ConfigurationManager.AppSettings["ClientCount"]);
            var messageSize = int.Parse(ConfigurationManager.AppSettings["MessageSize"]);
            var messageCount = int.Parse(ConfigurationManager.AppSettings["MessageCount"]);
            var sleepMilliseconds = int.Parse(ConfigurationManager.AppSettings["SleepMilliseconds"]);
            var batchSize = int.Parse(ConfigurationManager.AppSettings["BatchSize"]);
            var message = new byte[messageSize];
            var actions = new List<Action>();

            for (var i = 0; i < parallelThreadCount; i++)
            {
                var client = new SocketRemotingClient(new IPEndPoint(serverAddress, 5000));
                client.Start();
                actions.Add(() => SendMessages(client, mode, messageCount, sleepMilliseconds, batchSize, message));
            }

            _watch.Start();
            Parallel.Invoke(actions.ToArray());
            Console.ReadLine();
        }
Exemple #3
0
        static void SendMessages(SocketRemotingClient client, string mode, int count, int sleepMilliseconds, int batchSize, byte[] message)
        {
            _logger.Info("----Send message test----");

            if (mode == "Oneway")
            {
                for (var i = 1; i <= count; i++)
                {
                    TryAction(() => client.InvokeOneway(new RemotingRequest(100, message)));
                    Interlocked.Increment(ref _sentCount);
                    WaitIfNecessory(batchSize, sleepMilliseconds);
                }
            }
            else if (mode == "Async")
            {
                for (var i = 1; i <= count; i++)
                {
                    TryAction(() => client.InvokeAsync(new RemotingRequest(100, message), 100000).ContinueWith(SendCallback));
                    WaitIfNecessory(batchSize, sleepMilliseconds);
                }
            }
            else if (mode == "Callback")
            {
                client.RegisterResponseHandler(100, new ResponseHandler());
                for (var i = 1; i <= count; i++)
                {
                    TryAction(() => client.InvokeWithCallback(new RemotingRequest(100, message)));
                    WaitIfNecessory(batchSize, sleepMilliseconds);
                }
            }
        }
Exemple #4
0
        public Consumer(string groupName, ConsumerSetting setting)
        {
            if (groupName == null)
            {
                throw new ArgumentNullException("groupName");
            }
            GroupName = groupName;
            Setting = setting ?? new ConsumerSetting();

            _lockObject = new object();
            _subscriptionTopics = new Dictionary<string, HashSet<string>>();
            _topicQueuesDict = new ConcurrentDictionary<string, IList<MessageQueue>>();
            _pullRequestDict = new ConcurrentDictionary<string, PullRequest>();
            _remotingClient = new SocketRemotingClient(Setting.BrokerAddress, Setting.SocketSetting, Setting.LocalAddress);
            _adminRemotingClient = new SocketRemotingClient(Setting.BrokerAdminAddress, Setting.SocketSetting, Setting.LocalAdminAddress);
            _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
            _scheduleService = ObjectContainer.Resolve<IScheduleService>();
            _allocateMessageQueueStragegy = ObjectContainer.Resolve<IAllocateMessageQueueStrategy>();
            _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);

            _remotingClient.RegisterConnectionEventListener(new ConnectionEventListener(this));

            if (Setting.MessageHandleMode == MessageHandleMode.Sequential)
            {
                _consumingMessageQueue = new BlockingCollection<ConsumingMessage>();
                _consumeMessageWorker = new Worker("ConsumeMessage", () => HandleMessage(_consumingMessageQueue.Take()));
            }
            _messageRetryQueue = new BlockingCollection<ConsumingMessage>();
        }
Exemple #5
0
        public Consumer(string id, string groupName, ConsumerSetting setting)
        {
            if (id == null)
            {
                throw new ArgumentNullException("id");
            }
            if (groupName == null)
            {
                throw new ArgumentNullException("groupName");
            }
            Id = id;
            GroupName = groupName;
            Setting = setting ?? new ConsumerSetting();

            _lockObject = new object();
            _subscriptionTopics = new List<string>();
            _topicQueuesDict = new ConcurrentDictionary<string, IList<MessageQueue>>();
            _pullRequestQueue = new BlockingCollection<PullRequest>(new ConcurrentQueue<PullRequest>());
            _pullRequestDict = new ConcurrentDictionary<string, PullRequest>();
            _consumingMessageQueue = new BlockingCollection<ConsumingMessage>(new ConcurrentQueue<ConsumingMessage>());
            _messageRetryQueue = new BlockingCollection<ConsumingMessage>(new ConcurrentQueue<ConsumingMessage>());
            _handlingMessageDict = new ConcurrentDictionary<long, ConsumingMessage>();
            _taskIds = new List<int>();
            _taskFactory = new TaskFactory(new LimitedConcurrencyLevelTaskScheduler(Setting.ConsumeThreadMaxCount));
            _remotingClient = new SocketRemotingClient(Setting.BrokerConsumerIPEndPoint, null, this);
            _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
            _scheduleService = ObjectContainer.Resolve<IScheduleService>();
            _allocateMessageQueueStragegy = ObjectContainer.Resolve<IAllocateMessageQueueStrategy>();
            _executePullRequestWorker = new Worker("Consumer.ExecutePullRequest", ExecutePullRequest);
            _handleMessageWorker = new Worker("Consumer.HandleMessage", HandleMessage);
            _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);
            _waitSocketConnectHandle = new AutoResetEvent(false);
        }
Exemple #6
0
 public MessageService(IBinarySerializer binarySerializer)
 {
     _remotingClient = new SocketRemotingClient(Settings.BrokerAddress, Settings.BrokerPort);
     _remotingClient.Connect();
     _remotingClient.Start();
     _binarySerializer = binarySerializer;
 }
Exemple #7
0
 public MessageService(IBinarySerializer binarySerializer, IScheduleService scheduleService, SendEmailService sendEmailService)
 {
     _remotingClient = new SocketRemotingClient(Settings.BrokerAddress);
     _binarySerializer = binarySerializer;
     _scheduleService = scheduleService;
     _unconsumedMessageWarnningThreshold = int.Parse(ConfigurationManager.AppSettings["unconsumedMessageWarnningThreshold"]);
     _checkUnconsumedMessageInterval = int.Parse(ConfigurationManager.AppSettings["checkUnconsumedMessageInterval"]);
     _sendEmailService = sendEmailService;
 }
 public static IEnumerable<SocketRemotingClient> CreateRemotingClientList(IEnumerable<IPEndPoint> endpointList, SocketSetting socketSetting)
 {
     var remotingClientList = new List<SocketRemotingClient>();
     foreach (var endpoint in endpointList)
     {
         var remotingClient = new SocketRemotingClient(endpoint, socketSetting);
         remotingClientList.Add(remotingClient);
     }
     return remotingClientList;
 }
Exemple #9
0
 public Producer(ProducerSetting setting, string id)
 {
     Id = id;
     Setting = setting ?? new ProducerSetting();
     _topicQueueCountDict = new ConcurrentDictionary<string, int>();
     _taskIds = new List<int>();
     _remotingClient = new SocketRemotingClient(Setting.BrokerAddress, Setting.BrokerPort);
     _scheduleService = ObjectContainer.Resolve<IScheduleService>();
     _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
     _queueSelector = ObjectContainer.Resolve<IQueueSelector>();
     _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().Name);
 }
Exemple #10
0
 public Consumer(string id, ConsumerSetting setting, string groupName)
 {
     Id = id;
     Setting = setting ?? new ConsumerSetting();
     GroupName = groupName;
     _remotingClient = new SocketRemotingClient(Setting.BrokerAddress, Setting.BrokerPort);
     _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
     _scheduleService = ObjectContainer.Resolve<IScheduleService>();
     _offsetStore = Setting.MessageModel == MessageModel.Clustering ? ObjectContainer.Resolve<IRemoteBrokerOffsetStore>() as IOffsetStore : ObjectContainer.Resolve<ILocalOffsetStore>() as IOffsetStore;
     _allocateMessageQueueStragegy = ObjectContainer.Resolve<IAllocateMessageQueueStrategy>();
     _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().Name);
 }
Exemple #11
0
        public Producer(ProducerSetting setting)
        {
            Setting = setting ?? new ProducerSetting();

            _topicQueueIdsDict = new ConcurrentDictionary<string, IList<int>>();
            _remotingClient = new SocketRemotingClient(Setting.BrokerAddress, Setting.SocketSetting, Setting.LocalAddress);
            _adminRemotingClient = new SocketRemotingClient(Setting.BrokerAdminAddress, Setting.SocketSetting, Setting.LocalAdminAddress);
            _scheduleService = ObjectContainer.Resolve<IScheduleService>();
            _queueSelector = ObjectContainer.Resolve<IQueueSelector>();
            _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);

            _remotingClient.RegisterConnectionEventListener(new ConnectionEventListener(this));
        }
Exemple #12
0
 private SocketRemotingClientWrapper CreateReplyRemotingClient(IPEndPoint replyEndpoint)
 {
     return _clientWrapperDict.GetOrAdd(replyEndpoint.ToString(), key =>
     {
         var remotingClient = new SocketRemotingClient(replyEndpoint).Start();
         return new SocketRemotingClientWrapper
         {
             ReplyEndpoint = replyEndpoint,
             RemotingClient = remotingClient,
             LastActiveTime = DateTime.Now
         };
     });
 }
Exemple #13
0
        public Producer(string id, ProducerSetting setting)
        {
            if (id == null)
            {
                throw new ArgumentNullException("id");
            }
            Id = id;
            Setting = setting ?? new ProducerSetting();

            _lockObject = new object();
            _taskIds = new List<int>();
            _topicQueueIdsDict = new ConcurrentDictionary<string, IList<int>>();
            _remotingClient = new SocketRemotingClient(Setting.BrokerProducerIPEndPoint, null, this);
            _scheduleService = ObjectContainer.Resolve<IScheduleService>();
            _queueSelector = ObjectContainer.Resolve<IQueueSelector>();
            _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);
        }
Exemple #14
0
        public Producer(string id, ProducerSetting setting)
        {
            if (id == null)
            {
                throw new ArgumentNullException("id");
            }
            Id = id;
            Setting = setting ?? new ProducerSetting();

            _lockObject = new object();
            _topicQueueIdsDict = new ConcurrentDictionary<string, IList<int>>();
            _remotingClient = new SocketRemotingClient(Id + ".RemotingClient", Setting.BrokerAddress, Setting.LocalAddress);
            _scheduleService = ObjectContainer.Resolve<IScheduleService>();
            _queueSelector = ObjectContainer.Resolve<IQueueSelector>();
            _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);

            _remotingClient.RegisterConnectionEventListener(new ConnectionEventListener(this));
        }
Exemple #15
0
 public Consumer(string id, string groupName, ConsumerSetting setting)
 {
     if (id == null)
     {
         throw new ArgumentNullException("id");
     }
     if (groupName == null)
     {
         throw new ArgumentNullException("groupName");
     }
     Id = id;
     GroupName = groupName;
     Setting = setting ?? new ConsumerSetting();
     _remotingClient = new SocketRemotingClient(Setting.BrokerAddress, Setting.BrokerPort);
     _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
     _scheduleService = ObjectContainer.Resolve<IScheduleService>();
     _localOffsetStore = ObjectContainer.Resolve<ILocalOffsetStore>();
     _allocateMessageQueueStragegy = ObjectContainer.Resolve<IAllocateMessageQueueStrategy>();
     _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);
 }
Exemple #16
0
        public PullRequest(
            string consumerId,
            string groupName,
            MessageQueue messageQueue,
            SocketRemotingClient remotingClient,
            MessageHandleMode messageHandleMode,
            IMessageHandler messageHandler,
            IOffsetStore offsetStore,
            PullRequestSetting setting)
        {
            ConsumerId = consumerId;
            GroupName = groupName;
            MessageQueue = messageQueue;
            ProcessQueue = new ProcessQueue();

            _queueOffset = -1;
            _remotingClient = remotingClient;
            _setting = setting;
            _messageHandleMode = messageHandleMode;
            _messageHandler = messageHandler;
            _offsetStore = offsetStore;
            _messageQueue = new BlockingCollection<WrappedMessage>(new ConcurrentQueue<WrappedMessage>());
            _handlingMessageDict = new ConcurrentDictionary<long, WrappedMessage>();
            _pullMessageWorker = new Worker(() =>
            {
                try
                {
                    PullMessage();
                }
                catch (Exception ex)
                {
                    if (!_stoped)
                    {
                        _logger.Error(string.Format("[{0}]: PullMessage has unknown exception. PullRequest: {1}.", ConsumerId, this), ex);
                    }
                }
            });
            _handleMessageWorker = new Worker(HandleMessage);
            _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
            _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().Name);
        }
Exemple #17
0
        static void Main(string[] args)
        {
            var maxSendPacketSize = int.Parse(ConfigurationManager.AppSettings["MaxSendPacketSize"]);
            var socketBufferSize = int.Parse(ConfigurationManager.AppSettings["SocketBufferSize"]);
            var setting = new Setting
            {
                TcpConfiguration = new TcpConfiguration
                {
                    MaxSendPacketSize = maxSendPacketSize,
                    SocketBufferSize = socketBufferSize
                }
            };
            ECommonConfiguration
                .Create(setting)
                .UseAutofac()
                .RegisterCommonComponents()
                .UseLog4Net()
                .RegisterUnhandledExceptionHandler();

            var serverIP = ConfigurationManager.AppSettings["ServerAddress"];
            var mode = ConfigurationManager.AppSettings["Mode"];
            var ipAddress = string.IsNullOrEmpty(serverIP) ? SocketUtils.GetLocalIPV4() : IPAddress.Parse(serverIP);
            _remotingClient = new SocketRemotingClient(new IPEndPoint(ipAddress, 5000));
            _remotingClient.Start();

            var parallelThreadCount = int.Parse(ConfigurationManager.AppSettings["ParallelThreadCount"]);
            var actions = new List<Action>();
            for (var i = 0; i < parallelThreadCount; i++)
            {
                actions.Add(() => SendMessageAsync(mode));
            }

            _watch.Start();
            Parallel.Invoke(actions.ToArray());
            Console.ReadLine();
        }
Exemple #18
0
 public BrokerConnection(BrokerInfo brokerInfo, SocketRemotingClient remotingClient, SocketRemotingClient adminRemotingClient)
 {
     _brokerInfo = brokerInfo;
     _remotingClient = remotingClient;
     _adminRemotingClient = adminRemotingClient;
 }
Exemple #19
0
        private BrokerConnection BuildAndStartBrokerConnection(BrokerInfo brokerInfo)
        {
            IPEndPoint brokerEndpoint;
            if (_producer != null)
            {
                brokerEndpoint = brokerInfo.ProducerAddress.ToEndPoint();
            }
            else if (_consumer != null)
            {
                brokerEndpoint = brokerInfo.ConsumerAddress.ToEndPoint();
            }
            else
            {
                throw new Exception("ClientService must set producer or consumer.");
            }
            var brokerAdminEndpoint = brokerInfo.AdminAddress.ToEndPoint();
            var remotingClient = new SocketRemotingClient(brokerEndpoint, _setting.SocketSetting);
            var adminRemotingClient = new SocketRemotingClient(brokerAdminEndpoint, _setting.SocketSetting);
            var brokerConnection = new BrokerConnection(brokerInfo, remotingClient, adminRemotingClient);

            if (_producer != null && _producer.ResponseHandler != null)
            {
                remotingClient.RegisterResponseHandler((int)BrokerRequestCode.SendMessage, _producer.ResponseHandler);
            }

            brokerConnection.Start();

            return brokerConnection;
        }
Exemple #20
0
        static void SendMessageTest()
        {
            _mode = ConfigurationManager.AppSettings["Mode"];

            var serverIP = ConfigurationManager.AppSettings["ServerAddress"];
            var serverAddress = string.IsNullOrEmpty(serverIP) ? SocketUtils.GetLocalIPV4() : IPAddress.Parse(serverIP);
            var clientCount = int.Parse(ConfigurationManager.AppSettings["ClientCount"]);
            var messageSize = int.Parse(ConfigurationManager.AppSettings["MessageSize"]);
            var messageCount = int.Parse(ConfigurationManager.AppSettings["MessageCount"]);
            var sleepMilliseconds = int.Parse(ConfigurationManager.AppSettings["SleepMilliseconds"]);
            var batchSize = int.Parse(ConfigurationManager.AppSettings["BatchSize"]);
            var message = new byte[messageSize];
            var actions = new List<Action>();

            for (var i = 1; i <= clientCount; i++)
            {
                var client = new SocketRemotingClient("Client" + i.ToString(), new IPEndPoint(serverAddress, 5000));
                client.Start();
                actions.Add(() => SendMessages(client, _mode, messageCount, sleepMilliseconds, batchSize, message));
            }

            Parallel.Invoke(actions.ToArray());
        }
 public ConnectionEventListener(SocketRemotingClient remotingClient)
 {
     _remotingClient = remotingClient;
 }
Exemple #22
0
        static void SendMessages(SocketRemotingClient client, string mode, int count, int sleepMilliseconds, int batchSize, byte[] message)
        {
            Console.WriteLine("----Send message test----");

            if (mode == "Oneway")
            {
                for (var i = 1; i <= count; i++)
                {
                    TryAction(() => client.InvokeOneway(new RemotingRequest(100, message)));
                    var current = Interlocked.Increment(ref _totalReceivedCount);
                    if (current % 10000 == 0)
                    {
                        Console.WriteLine("Sent {0} messages, timeSpent: {1}ms", current, _watch.ElapsedMilliseconds);
                    }
                    WaitIfNecessory(batchSize, sleepMilliseconds);
                }
            }
            else if (mode == "Async")
            {
                for (var i = 1; i <= count; i++)
                {
                    TryAction(() => client.InvokeAsync(new RemotingRequest(100, message), 100000).ContinueWith(SendCallback));
                    WaitIfNecessory(batchSize, sleepMilliseconds);
                }
            }
            else if (mode == "Callback")
            {
                client.RegisterResponseHandler(100, new ResponseHandler());
                for (var i = 1; i <= count; i++)
                {
                    TryAction(() => client.InvokeWithCallback(new RemotingRequest(100, message)));
                    WaitIfNecessory(batchSize, sleepMilliseconds);
                }
            }
        }
Exemple #23
0
 private IEnumerable<int> CreateTopicOnBroker(string topic, Broker broker)
 {
     var brokerAdminEndpoint = broker.BrokerInfo.AdminAddress.ToEndPoint();
     var adminRemotingClient = new SocketRemotingClient(brokerAdminEndpoint, _nameServerController.Setting.SocketSetting).Start();
     var requestData = _binarySerializer.Serialize(new CreateTopicRequest(topic));
     var remotingRequest = new RemotingRequest((int)BrokerRequestCode.CreateTopic, requestData);
     var remotingResponse = adminRemotingClient.InvokeSync(remotingRequest, 30000);
     if (remotingResponse.Code != ResponseCode.Success)
     {
         throw new Exception(string.Format("AutoCreateTopicOnBroker failed, errorMessage: {0}", Encoding.UTF8.GetString(remotingResponse.Body)));
     }
     adminRemotingClient.Shutdown();
     return _binarySerializer.Deserialize<IEnumerable<int>>(remotingResponse.Body);
 }
Exemple #24
0
 public MessageService(IBinarySerializer binarySerializer)
 {
     _remotingClient = new SocketRemotingClient(Settings.BrokerAddress);
     _binarySerializer = binarySerializer;
 }
Exemple #25
0
        private void RefreshClusterBrokers(string clusterName)
        {
            var remotingClient = GetAvailableNameServerRemotingClient();
            var requestData = _binarySerializer.Serialize(new GetClusterBrokersRequest { ClusterName = clusterName });
            var remotingRequest = new RemotingRequest((int)NameServerRequestCode.GetClusterBrokers, requestData);
            var remotingResponse = remotingClient.InvokeSync(remotingRequest, 30000);

            if (remotingResponse.Code == ResponseCode.Success)
            {
                var brokerInfoList = _binarySerializer.Deserialize<IEnumerable<BrokerInfo>>(remotingResponse.Body);
                var brokerClientList = new List<BrokerClient>();
                foreach (var brokerInfo in brokerInfoList)
                {
                    var client = new SocketRemotingClient(brokerInfo.AdminAddress.ToEndPoint(), Settings.SocketSetting).Start();
                    var brokerClient = new BrokerClient { BrokerInfo = brokerInfo, RemotingClient = client };
                    brokerClientList.Add(brokerClient);
                }
                IList<BrokerClient> removedList;
                if (_clusterBrokerDict.TryRemove(clusterName, out removedList))
                {
                    foreach (var brokerClient in removedList)
                    {
                        brokerClient.RemotingClient.Shutdown();
                    }
                }
                _clusterBrokerDict.TryAdd(clusterName, brokerClientList);
            }
            else
            {
                throw new Exception(string.Format("GetClusterBrokers failed, errorMessage: {0}", Encoding.UTF8.GetString(remotingResponse.Body)));
            }
        }
Exemple #26
0
        static void StartSendMessageTest()
        {
            var serverIP = ConfigurationManager.AppSettings["ServerAddress"];
            var serverAddress = string.IsNullOrEmpty(serverIP) ? SocketUtils.GetLocalIPV4() : IPAddress.Parse(serverIP);
            var sendAction = default(Action);

            _client = new SocketRemotingClient(new IPEndPoint(serverAddress, 5000)).Start();

            if (_mode == "Oneway")
            {
                sendAction = () =>
                {
                    var request = new RemotingRequest(100, _message);
                    _client.InvokeOneway(request);
                    _performanceService.IncrementKeyCount(_performanceKey, (DateTime.Now - request.CreatedTime).TotalMilliseconds);
                };
            }
            else if (_mode == "Sync")
            {
                sendAction = () =>
                {
                    var request = new RemotingRequest(100, _message);
                    var response = _client.InvokeSync(request, 5000);
                    _performanceService.IncrementKeyCount(_performanceKey, (DateTime.Now - response.RequestTime).TotalMilliseconds);
                };
            }
            else if (_mode == "Async")
            {
                sendAction = () =>
                {
                    var request = new RemotingRequest(100, _message);
                    _client.InvokeAsync(request, 100000).ContinueWith(t =>
                    {
                        if (t.Exception != null)
                        {
                            _logger.Error(t.Exception);
                            return;
                        }
                        var response = t.Result;
                        if (response.ResponseCode <= 0)
                        {
                            _logger.Error(Encoding.UTF8.GetString(response.ResponseBody));
                            return;
                        }
                        _performanceService.IncrementKeyCount(_performanceKey, (DateTime.Now - response.RequestTime).TotalMilliseconds);
                    });
                };
            }
            else if (_mode == "Callback")
            {
                _client.RegisterResponseHandler(100, new ResponseHandler(_performanceService, _performanceKey));
                sendAction = () => _client.InvokeWithCallback(new RemotingRequest(100, _message));
            }

            Task.Factory.StartNew(() =>
            {
                for (var i = 0; i < _messageCount; i++)
                {
                    try
                    {
                        sendAction();
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorFormat("Send remotingRequest failed, errorMsg:{0}", ex.Message);
                        Thread.Sleep(3000);
                    }
                }
            });
        }
 public ConnectionEventListener(SocketRemotingClient remotingClient)
 {
     _remotingClient = remotingClient;
 }
Exemple #28
0
        static void StartSendMessageTest()
        {
            var serverIP = ConfigurationManager.AppSettings["ServerAddress"];
            var serverAddress = string.IsNullOrEmpty(serverIP) ? SocketUtils.GetLocalIPV4() : IPAddress.Parse(serverIP);
            var messageSize = int.Parse(ConfigurationManager.AppSettings["MessageSize"]);

            _message = new byte[messageSize];
            _mode = ConfigurationManager.AppSettings["Mode"];
            _messageCount = int.Parse(ConfigurationManager.AppSettings["MessageCount"]);

            _client = new SocketRemotingClient(new IPEndPoint(serverAddress, 5000)).Start();

            var sendAction = default(Action);

            if (_mode == "Oneway")
            {
                sendAction = () =>
                {
                    _client.InvokeOneway(new RemotingRequest(100, _message));
                    Interlocked.Increment(ref _sentCount);
                };
            }
            else if (_mode == "Sync")
            {
                sendAction = () =>
                {
                    _client.InvokeSync(new RemotingRequest(100, _message), 5000);
                    Interlocked.Increment(ref _sentCount);
                };
            }
            else if (_mode == "Async")
            {
                sendAction = () => _client.InvokeAsync(new RemotingRequest(100, _message), 100000).ContinueWith(t =>
                {
                    if (t.Exception != null)
                    {
                        _logger.Error(t.Exception);
                        return;
                    }
                    if (t.Result.Code <= 0)
                    {
                        _logger.Error(Encoding.UTF8.GetString(t.Result.Body));
                        return;
                    }
                    Interlocked.Increment(ref _sentCount);
                });
            }
            else if (_mode == "Callback")
            {
                _client.RegisterResponseHandler(100, new ResponseHandler());
                sendAction = () => _client.InvokeWithCallback(new RemotingRequest(100, _message));
            }

            Task.Factory.StartNew(() =>
            {
                for (var i = 0; i < _messageCount; i++)
                {
                    try
                    {
                        sendAction();
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorFormat("Send remoting request failed, errorMsg:{0}", ex.Message);
                        Thread.Sleep(3000);
                    }
                }
            });
        }