Esempio n. 1
0
        /// <summary>
        /// 启动
        /// </summary>
        public void Start()
        {
            if (Interlocked.CompareExchange(ref _isRunning, 1, 0) == 0)
            {
                if (_amqpConnection == null)
                {
                    var connFactory = new RabbitMQConnectionFactory
                    {
                        Uri = _amqpUri
                    };
                    _amqpConnection = connFactory.CreateConnection(_clientName);
                    _selfCreate     = true;
                }

                if (_autoConfig)
                {
                    using (var channelForConfig = _amqpConnection.CreateModel())
                    {
                        foreach (var topic in _topics.Keys)
                        {
                            var queueCount      = _topics[topic];
                            var subscribeQueues = GetSubscribeQueues(queueCount, _consumerCount, _consumerSequence);
                            var subTopic        = GetSubTopic(topic);
                            channelForConfig.ExchangeDeclare(topic, ExchangeType.Fanout, true, false, null);
                            channelForConfig.ExchangeDeclare(subTopic, ExchangeType.Direct, true, false, null);
                            channelForConfig.ExchangeBind(subTopic, topic, "", null);

                            for (byte queueIndex = 0; queueIndex < queueCount; queueIndex++)
                            {
                                string queueName = GetQueue(topic, queueIndex);
                                channelForConfig.QueueDeclare(queueName, true, false, false, null);
                                channelForConfig.QueueBind(queueName, subTopic, queueIndex.ToString(), null);
                            }
                        }
                        channelForConfig.Close();
                    }
                }

                if (_mode == ConsumeMode.Push)
                {
                    ConsumeByPush();
                }
                else
                {
                    ConsumeByPull();
                }
            }
        }
        /// <summary>
        /// Registers the mq listen and hubs.
        /// </summary>
        public static void RegisterMQListenAndHubs()
        {
            ConnectionFactory factory = new ConnectionFactory();

            factory.UserName = "******";
            // "gue
            factory.Password    = "******";
            factory.VirtualHost = "/";
            factory.HostName    = "192.168.1.105";
            RabbitMQ.Client.IConnection conn = factory.CreateConnection();
            IModel channel  = conn.CreateModel();
            var    consumer = new EventingBasicConsumer(channel);

            consumer.Received += (ch, ea) =>
            {
                var body = ea.Body;

                if (body != null)
                {
                    string message = System.Text.Encoding.Default.GetString(body);

                    GlobalHost.ConnectionManager.GetHubContext <RealTimeDataHub>().Clients.All.realData(message);
                }

                ((IModel)ch).BasicAck(ea.DeliveryTag, false);
            };

            String consumerTag = channel.BasicConsume("lenovo", false, consumer);
        }
Esempio n. 3
0
        } // AmqpClient

        #region ConnectionHandlerProgram

        private Exception MakeNewConnection(ref RmqCl.IConnection connection, ref RmqCl.IModel channel, bool reconnecting)
        {
            // This method attempts to make a new connection. Returns true if success, otherwise false.

            var connRequest = ConnectionRequestObj;

            var factory = new RmqCl.ConnectionFactory()
            {
                HostName = connRequest.Host,
                UserName = connRequest.Username,
                Password = connRequest.Password
            };

            // Secure connection?
            if (connRequest.Secure)
            {
                factory.Ssl.Enabled    = true;
                factory.Ssl.ServerName = connRequest.Host;
                factory.Ssl.Version    = System.Security.Authentication.SslProtocols.Tls12;
            }

            try
            {
                // Create connection and channel
                connection = factory.CreateConnection();
                channel    = connection.CreateModel();

                // Declare the exchange
                channel.ExchangeDeclare(exchange: connRequest.Exchange, type: "topic", autoDelete: false, durable: true, arguments: null);

                // Create a queue to receive messages
                var queueName = channel.QueueDeclare(queue: "",        // Use a generated queue name
                                                     durable: false,   // The queue does not survive a broker restart
                                                     exclusive: true,  // The queue is only for this application, and it will be deleted on app exit
                                                     autoDelete: true, // The queue is deleted when no one is bound to it
                                                     arguments: null
                                                     ).QueueName;

                // Bind the queue to the topic pattern
                channel.QueueBind(queue: queueName, exchange: connRequest.Exchange, routingKey: connRequest.TopicPattern, arguments: null);

                // Set up a consumer for messages
                m_messageConsumer           = new RmqCl.Events.EventingBasicConsumer(channel);
                m_messageConsumer.Received += MessageReceived;
                channel.BasicConsume(queue: queueName, noAck: true, consumerTag: "", noLocal: false, exclusive: false, arguments: new Dictionary <string, object> {
                }, consumer: m_messageConsumer);

                // Sign up for the shutdown event
                channel.ModelShutdown += ModelShutdown; // This event will fire if the connection is lost

                return(null);
            }
            catch (Exception e)
            {
                // Clean the connection
                DestroyConnection(ref connection, ref channel);

                return(e);
            }
        } // MakeNewConnection
Esempio n. 4
0
        private static void WriteMessage(RabbitMQ.Client.IConnection conn, string from)
        {
            Console.Write("To: ");
            var to = Console.ReadLine();

            if (String.IsNullOrEmpty(to))
            {
                return;
            }

            Console.Write("Message: ");
            var message = Console.ReadLine();

            try
            {
                using (var model = conn.CreateModel())
                {
                    model.BasicReturn += new EventHandler <RabbitMQ.Client.Events.BasicReturnEventArgs>(blabla);

                    var rabbitMessage = new RabbitMessage()
                    {
                        From = from, Message = message
                    };
                    var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(rabbitMessage));
                    model.BasicPublish(to + "Exchange", string.Empty, new BasicProperties()
                    {
                        DeliveryMode = 2
                    }, body);
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
        }
Esempio n. 5
0
        public void DeleteQueue(IStreamConfig config)
        {
            var rabbitConfig = config as RabbitConfig;
            var channel      = _connection.CreateModel();

            channel.QueueDelete(rabbitConfig.QueueName);
        }
        public string CreateConsumerChannel()
        {
            var message = "";

            //CreateConnection();

            using (var channel = _connection.CreateModel())
            {
                channel.ExchangeDeclare(ExchangeName, type: "fanout", true);

                channel.QueueDeclare(queue: ExchangeName,
                                     durable: true,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);

                channel.QueueBind(queue: ExchangeName, exchange: ExchangeName, routingKey: "", arguments: null);

                var consumer = new EventingBasicConsumer(channel);
                channel.BasicConsume(ExchangeName, false, consumer);



                consumer.Received += (model, ea) =>
                {
                    //var eventName = ea.RoutingKey;
                    message += Encoding.UTF8.GetString(ea.Body);
                    channel.BasicAck(ea.DeliveryTag, multiple: false);
                };

                channel.QueuePurge(ExchangeName);
            }

            return(message);
        }
        /// <summary>
        /// 创建渠道并添加到渠道列表里
        /// </summary>
        /// <returns>渠道</returns>
        private IModel CreateChannel()
        {
            IModel channel = connection.CreateModel();

            channels.Add(channel);

            return(channel);
        }
Esempio n. 8
0
        //options
        internal IModel CreateChannel(IConnection connection)
        {
            var channel = connection.CreateModel();

            channel.QueueDeclare(QueueName, Durable, Exclusive, AutoDelete, Arguments);

            //configure channel using options here
            return(channel);
        }
Esempio n. 9
0
        protected internal virtual IModel CreateInboundModel(RabbitMQ.Client.IConnection connection,
                                                             UInt32 prefetchSize,
                                                             UInt16 prefetchCount)
        {
            var model = connection.CreateModel();

            model.BasicQos(prefetchSize, prefetchCount, false);
            return(model);
        }
Esempio n. 10
0
        public static void CreateConnection()
        {
            _factory = new ConnectionFactory {
                HostName = "localhost", UserName = "******", Password = "******"
            };
            _connection = _factory.CreateConnection();

            _model = _connection.CreateModel();
            _model.ExchangeDeclare(ExchangeName, "fanout", true);
        }
        private RabbitMQClient CreateClient(string routingKey)
        {
            if (_connection is null)
            {
                throw new ObjectDisposedException(nameof(_connection));
            }
            //TODO - Handle possible CreateModel exceptions.
            var model = _connection.CreateModel();

            model.ExchangeDeclare(_exchange, Rabbit.ExchangeType.Topic, false, false, null); //TODO - Handle possible exceptions.
            return(new RabbitMQClient(_exchange, routingKey, model));
        }
Esempio n. 12
0
        /// <remarks>
        /// Only call this from a task in the taskQueue to ensure IModel is only used
        /// by a single thread, as is recommended in the RabbitMQ .NET Client documentation.
        /// </remarks>
        private async Task <IModel> GetChannel(int?maxAttempts = null)
        {
            if (channelInstance != null)
            {
                return(channelInstance);
            }

            var attempts          = 0;
            var connectionFactory = new ConnectionFactory
            {
                HostName    = ConnectionParams.HostName,
                Port        = ConnectionParams.Port,
                VirtualHost = ConnectionParams.VirtualHost,
                UserName    = ConnectionParams.Username,
                Password    = ConnectionParams.Password,
                AutomaticRecoveryEnabled = true, // The created connection is an IRecoverable
                RequestedHeartbeat       = 30
            };

            while (true)
            {
                try
                {
                    connection      = connectionFactory.CreateConnection();
                    channelInstance = connection.CreateModel();

                    if (ConnectionParams.PrefetchCount > 0)
                    {
                        channelInstance.BasicQos(0, ConnectionParams.PrefetchCount, false);
                    }

                    ((IRecoverable)connection).Recovery += (sender, e) => ConnectionEventListener?.Reconnected();

                    channelInstance.ModelShutdown += (sender, e) => ConnectionEventListener?.Disconnected();

                    ConnectionEventListener?.Connected();
                    break;
                }
                catch (BrokerUnreachableException)
                {
                    attempts++;
                    if (maxAttempts.HasValue && attempts > maxAttempts.Value)
                    {
                        throw;
                    }

                    await Task.Delay(ReconnectDelay);
                }
            }

            return(channelInstance);
        }
Esempio n. 13
0
        private void SetupChannel()
        {
            if (_channel != null && _channel.IsOpen)
            {
                return;
            }

            _channel?.Dispose();
            SetupConnection();

            _channel = _connection.CreateModel();
            _logger.LogInformation("Channel is ready");
        }
Esempio n. 14
0
        public RabbitMQWrapper(RabbitMQ.Client.IConnection connection)
        {
            _rmqConnection = connection;
            _rmqModel      = _rmqConnection.CreateModel();

            _rmqModel.ExchangeDeclare(_exchangeName, ExchangeType.Topic);

            _serializerSettings = new JsonSerializerSettings
            {
                ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                NullValueHandling = NullValueHandling.Ignore
            };
        }
Esempio n. 15
0
        /// <summary>
        /// 启动
        /// </summary>
        public void Start()
        {
            if (Interlocked.CompareExchange(ref _isRunning, 1, 0) == 0)
            {
                if (_amqpConnection == null)
                {
                    var connFactory = new RabbitMQConnectionFactory
                    {
                        Uri = _amqpUri
                    };
                    _amqpConnection = connFactory.CreateConnection(_clientName);
                    _selfCreate     = true;
                }

                if (_autoConfig)
                {
                    foreach (var topic in _topics.Keys)
                    {
                        using (var channelForConfig = _amqpConnection.CreateModel())
                        {
                            channelForConfig.ExchangeDeclare(topic, ExchangeType.Fanout, true, false, null);
                            if (_delayedMessageEnabled)
                            {
                                channelForConfig.ExchangeDeclare($"{topic}-delayed", "x-delayed-message", true, false, new Dictionary <string, object>
                                {
                                    { "x-delayed-type", ExchangeType.Fanout }
                                });
                                channelForConfig.ExchangeBind(topic, $"{topic}-delayed", "", null);
                            }
                            channelForConfig.Close();
                        }
                    }
                }
                _cleanIdleChannelTimer.Change(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
            }
        }
Esempio n. 16
0
 /// <summary>
 /// 每次重启时,清空队列
 /// </summary>
 public static void DeleteQueue()
 {
     using (IConnection conn = RabbitMqFactory.CreateConnection())
     {
         using (IModel channel = conn.CreateModel())
         {
             try
             {
                 channel.QueueDelete(QueueName, true, false);
             }
             catch (Exception e)
             {
                 LogWrite.WriteLogInfo($"重启时,存在消费者,不删除队列,异常{e.Message}");
             }
         }
     }
 }
Esempio n. 17
0
        public void CreateConnection()
        {
            _factory = new ConnectionFactory
            {
                HostName = "40.114.125.124",
                UserName = "******",
                Password = "******"
            };

            _connection = _factory.CreateConnection();
            _channel    = _connection.CreateModel();

            _httpClient = new HttpClient
            {
                BaseAddress = new Uri("http://servinteframeworkstorageapi.azurewebsites.net")
            };
        }
Esempio n. 18
0
 public EventConsumer()
 {
     _factory = new ConnectionFactory
     {
         HostName = HostName,
         UserName = UserName,
         Password = Password
     };
     _connection = _factory.CreateConnection();
     _model      = _connection.CreateModel();
     _model.QueueDeclare(QueueName, true, false, false, null);
     _model.QueueBind(QueueName, ExchangeName, "");
     _model.BasicQos(0, 1, false);
     _subscription   = new Subscription(_model, QueueName, false);
     _gameRepository = new MongoRepository <HSGame>();
     _deckRepository = new MongoRepository <HSDeck>();
 }
        public RabbitMqMessageBus(IDependencyResolver resolver, RabbitMqScaleoutConfiguration configuration)
            : base(resolver, configuration)
        {
            Open(0);

            var connectionFactory = CreateConnectionFactory(configuration);

            connection = connectionFactory.CreateConnection();

            model = connection.CreateModel();

            model.QueueDeclare(configuration.QueueName, false, false, true, new Hashtable());
            model.ExchangeDeclare(configuration.ExchangeName, ExchangeType.Fanout);
            model.QueueBind(configuration.QueueName, configuration.ExchangeName, "");

            consumerTag = model.BasicConsume(configuration.QueueName, true, new Consumer(this.OnReceived));

            this.configuration = configuration;
        }
Esempio n. 20
0
        private void InitRabbitMQ()
        {
            var _connectionFactory = new ConnectionFactory()
            {
                HostName = _configuration["RabbitMQ:HostName"],
                Port     = int.Parse(_configuration["RabbitMQ:Port"]),
                UserName = _configuration["RabbitMQ:UserName"],
                Password = _configuration["RabbitMQ:Password"]
            };

            // create connection
            _connection = _connectionFactory.CreateConnection();

            // create channel
            _channel = _connection.CreateModel();

            var exchange   = _configuration["RabbitMQ:Logs:Exchange"];
            var queue      = _configuration["RabbitMQ:Logs:Queue"];
            var routingKey = _configuration["RabbitMQ:Logs:RoutingKey"];

            _channel.ExchangeDeclare(
                exchange: exchange,
                type: ExchangeType.Topic,
                durable: true,
                autoDelete: false,
                arguments: null);

            _channel.QueueDeclare(
                queue: queue,
                durable: true,
                exclusive: false,
                autoDelete: false,
                arguments: null);

            _channel.QueueBind(queue: queue,
                               exchange: exchange,
                               routingKey: routingKey,
                               arguments: null);

            _channel.BasicQos(0, 1, false);

            _connection.ConnectionShutdown += RabbitMQ_ConnectionShutdown;
        }
Esempio n. 21
0
        //测试方法
//        public Task Execute(IJobExecutionContext context)
//        {
//            Console.WriteLine("微信推送");
//
//            #region 测试
//            var stockSignalSingles = MongoService.GetAllStockSignalSingle();
//            var model1 = stockSignalSingles.FirstOrDefault();
//            var model2 = stockSignalSingles.Last();
//            List<stock_signal_single> list = new List<stock_signal_single>
//            {
//                model1,model2
//            };
//            DirectExchangeSendMsg(list);
//            #endregion
//
//
//            return Task.FromResult(0);
//        }

        public static void DirectExchangeSendMsg(List <stock_signal_single> signalNowList)
        {
            using (IConnection conn = RabbitMqFactory.CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {
                    channel.ExchangeDeclare(ExchangeName, "direct", durable: true, autoDelete: false, arguments: null);
                    channel.QueueDeclare(QueueName, durable: true, autoDelete: false, exclusive: false, arguments: null);
                    channel.QueueBind(QueueName, ExchangeName, routingKey: "signalList");
                    var props = channel.CreateBasicProperties();

                    props.Persistent = true;
                    var listToJson = JsonConvert.SerializeObject(signalNowList);
                    var msgBody    = BinarySerializeHelper.SerializeObject(listToJson);

                    channel.BasicPublish(exchange: ExchangeName, routingKey: "signalList", basicProperties: props, body: msgBody);
                }
            }
        }
        public RabbitMqMessageBus(IDependencyResolver resolver, RabbitMqScaleoutConfiguration configuration)
            : base(resolver, configuration)
        {
            Open(0);
            
            var connectionFactory = CreateConnectionFactory(configuration);

            connection = connectionFactory.CreateConnection();

            model = connection.CreateModel();

            var exchange = configuration.ExchangeName ?? "messages";

            model.QueueDeclare(configuration.QueueName, false, false, true, new Hashtable());
            model.ExchangeDeclare(exchange, ExchangeType.Fanout);
            model.QueueBind(configuration.QueueName, exchange, "");

            consumerTag = model.BasicConsume(configuration.QueueName, true, new Consumer(this.OnReceived));
        }
Esempio n. 23
0
        public MessageBroker(ITypeDiscoverer typeDiscoverer, IContainer container)
        {
            var consumerTypes = typeDiscoverer.FindMultiple(typeof(IMessageConsumer <>));

            consumerTypes.ForEach(t =>
            {
                var messageType = t.GetInterface(typeof(IMessageConsumer <>).Name).GetGenericArguments()[0];
                List <object> consumers;
                if (!_consumersByMessageType.ContainsKey(messageType))
                {
                    consumers = new List <object>();
                    _consumersByMessageType[messageType] = consumers;
                }
                else
                {
                    consumers = _consumersByMessageType[messageType];
                }
                consumers.Add(container.Get(t));
            });
            _messageTypesByName = typeDiscoverer.FindMultiple(typeof(Message)).ToDictionary(t => t.Name, t => t);

            _topicName    = ConfigurationManager.AppSettings["RabbitMQTopic"];
            _consumerName = ConfigurationManager.AppSettings["RabbitMQQueue"];

            _connectionFactory = new ConnectionFactory()
            {
                HostName = ConfigurationManager.AppSettings["RabbitMQServer"],
                UserName = ConfigurationManager.AppSettings["RabbitMQUsername"],
                Password = ConfigurationManager.AppSettings["RabbitMQPassword"]
            };

            _connection = _connectionFactory.CreateConnection();
            _channel    = _connection.CreateModel();

            _channel.ExchangeDeclare(_topicName, "topic");
            _channel.QueueDeclare(_consumerName, true, false, false, null);
            _channel.QueueBind(_consumerName, _topicName, "*");

            _consumer = new QueueingBasicConsumer(_channel);
            _channel.BasicConsume(_consumerName, true, _consumer);

            ThreadPool.QueueUserWorkItem(Receiver);
        }
Esempio n. 24
0
        public ChatTicker(
            IMessageManager messageManager,
            IHubContext <IChatClient> hubContext,
            IRepository <ApplicationUser> userRepository)
        {
            this.messageManager = messageManager;
            this.hubContext     = hubContext;
            this.userRepository = userRepository;

            var factory = new ConnectionFactory()
            {
                HostName = Properties.Settings.Default.ChatBotServerUrl
            };

            this.connection = factory.CreateConnection();
            this.channel    = connection.CreateModel();
            this.consumer   = new EventingBasicConsumer(channel);

            this.ConfigureBotQueues();
        }
Esempio n. 25
0
        public static void DirectExchangeSendMsg()
        {
            using (IConnection conn = RabbitMqFactory.CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {
                    channel.ExchangeDeclare(ExchangeName, "direct", durable: true, autoDelete: false, arguments: null);
                    channel.QueueDeclare(QueueName, durable: true, autoDelete: false, exclusive: false, arguments: null);
                    channel.QueueBind(QueueName, ExchangeName, routingKey: "key1");
//                    channel.QueueDeclare(QueueName2, durable: true, autoDelete: false, exclusive: false, arguments: null);
//                    channel.QueueBind(QueueName2, ExchangeName, routingKey: "key2");

                    var props = channel.CreateBasicProperties();
                    props.Persistent = true;
                    var chgModel = Service.GetChgData();
                    var msgBody  = BinarySerializeHelper.SerializeObject(chgModel);
//                    var msgBody = Encoding.UTF8.GetBytes(bytes);
                    channel.BasicPublish(exchange: ExchangeName, routingKey: "key1", basicProperties: props, body: msgBody);
                }
            }
        }
Esempio n. 26
0
        public RC.IModel CreateChannel(bool transactional = false)
        {
            try
            {
                var result = _connection.CreateModel();
                if (result == null)
                {
                    throw new RabbitResourceNotAvailableException("The channelMax limit is reached. Try later.");
                }

                if (transactional)
                {
                    result.TxSelect();
                }

                return(result);
            }
            catch (Exception e)
            {
                throw RabbitExceptionTranslator.ConvertRabbitAccessException(e);
            }
        }
Esempio n. 27
0
        protected virtual void ConnectToBroker()
        {
            if (_outboundModel != null && !_outboundModel.IsClosed) return;
            _connection = _connectionBuilder.CreateConnection(_configuration.EndpointUri);
            //Logger.DebugFormat("RMQMessagingGateway: Opening channel to Rabbit MQ on connection {0}", Configuration.AMPQUri.GetSanitizedUri());
            _outboundModel = _connection.CreateModel();
            //When AutoClose is true, the last channel to close will also cause the connection to close1. If it is set to
            //true before any channel is created, the connection will close then and there.
            if (_connection.AutoClose == false)
                _connection.AutoClose = true;

            foreach (var exchange in _exchanges)
                exchange.Declare(_outboundModel);

            foreach (var queue in _queues)
                queue.Declare(_outboundModel);

            foreach (var binding in _bindings)
                binding.Declare(_outboundModel);

            var builder = new ConsumedMessageBuilder(_configuration.SerializationConfiguration, _configuration.MessageTypeResolver);
            _outboundChannel = _configuration.OutboundChannelBuilder(_outboundModel, _configuration);
            var consumers = _promises.Select(_ =>
            {
                var model = CreateInboundModel(_connection, _configuration.PrefetchSize, _configuration.PrefetchCount);
                var consumer = _(builder).BuildConsumer(new InboundChannel(model), _outboundChannel);
                return new {Model = model, Consumer = consumer};
            })
                .ToList();

            foreach (var consumer in consumers)
                consumer.Consumer.Declare(consumer.Model);
            _consumers = consumers.Select(_ => _.Consumer);
        }
Esempio n. 28
0
        private async Task Run(string[] args)
        {
            var host  = ConfigurationManager.AppSettings["rabbit.host"];
            var user  = ConfigurationManager.AppSettings["rabbit.admuser"];
            var pwd   = ConfigurationManager.AppSettings["rabbit.admpwd"];
            var vhost = ConfigurationManager.AppSettings["rabbit.vhost"];

            LogAdapter.LogDebugFn              = (s, s1, arg3) => { };
            LogAdapter.ExtendedLogEnabled      = false;
            LogAdapter.ProtocolLevelLogEnabled = false;

            _hdrHistogram = new LongHistogram(1, 1000 * 10, 5);

            int  howManyQueues        = 10;
            bool exclusiveConnections = ConfigurationManager.AppSettings["exclusiveConnections"] == "true";
            bool useOfficialClient    = ConfigurationManager.AppSettings["useOfficialClient"] == "true";

            if (useOfficialClient)
            {
                RabbitMQ.Client.IConnection conn    = null;
                RabbitMQ.Client.IModel      channel = null;

                for (int i = 0; i < howManyQueues; i++)
                {
                    var connFac = new RabbitMQ.Client.ConnectionFactory()
                    {
                        HostName = host, UserName = user, Password = pwd, VirtualHost = vhost, AutomaticRecoveryEnabled = false
                    };

                    if (exclusiveConnections || conn == null)
                    {
                        conn    = connFac.CreateConnection();
                        channel = conn.CreateModel();
                        channel.BasicQos(0, 300, false);
                    }

                    var q = "q." + i;
                    channel.QueueDeclareNoWait(q, durable: true, exclusive: false, autoDelete: false, arguments: null);

                    channel.BasicConsume(q, false, "con_" + q, arguments: null, consumer: new Consumer(channel));
                }
            }
            else
            {
                RabbitMqNext.IConnection conn    = null;
                RabbitMqNext.IChannel    channel = null;

                for (int i = 0; i < howManyQueues; i++)
                {
                    if (exclusiveConnections || conn == null)
                    {
                        conn = await RabbitMqNext.ConnectionFactory.Connect(host, vhost, user, pwd, recoverySettings : null, connectionName : "mod_perf_server");

                        channel = await conn.CreateChannel();

                        await channel.BasicQos(0, 300, false);
                    }

                    var q = "q." + i;

                    await channel.QueueDeclare(q, passive : false, durable : true, exclusive : false, autoDelete : false, arguments : null,
                                               waitConfirmation : false);

                    // TODO: test with parallel buffer copy + serialized too
                    await channel.BasicConsume(ConsumeMode.SerializedWithBufferCopy, BuildConsumerFn(channel), q, "consumer_" + q,
                                               false, true, arguments : null, waitConfirmation : false);
                }
            }

            Console.WriteLine("Consuming..");

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                Console.WriteLine("Done\r\n");
                Console.WriteLine("howManyQueues {0} exclusive Connections: {1} official client: {2} count {3}", howManyQueues, exclusiveConnections, useOfficialClient, _hdrHistogram.TotalCount);
                Console.WriteLine("\r\n");

                _hdrHistogram.OutputPercentileDistribution(Console.Out);

                Console.ReadKey();
            };

            await Task.Delay(1);

            Thread.CurrentThread.Join();
        }
Esempio n. 29
0
        private async Task Run(string[] args)
        {
            //
            // client side
            // publishes on different connections
            //

            LogAdapter.ExtendedLogEnabled      = false;
            LogAdapter.ProtocolLevelLogEnabled = false;
            LogAdapter.LogDebugFn = (s, s1, arg3) => { };

            var host  = ConfigurationManager.AppSettings["rabbit.host"];
            var user  = ConfigurationManager.AppSettings["rabbit.admuser"];
            var pwd   = ConfigurationManager.AppSettings["rabbit.admpwd"];
            var vhost = ConfigurationManager.AppSettings["rabbit.vhost"];

            var postWarmupDelay = TimeSpan.FromSeconds(5);

            int  howManyQueues        = 10;
            bool exclusiveConnections = ConfigurationManager.AppSettings["exclusiveConnections"] == "true";
            bool useOfficialClient    = ConfigurationManager.AppSettings["useOfficialClient"] == "true";

            var howManyCalls = 100000;

            _completionSemaphore = new SemaphoreSlim(0, howManyQueues);
            _startSync           = new ManualResetEventSlim(false);

            if (useOfficialClient)
            {
                // Warm up
//				{
//					var connFac = new RabbitMQ.Client.ConnectionFactory() { HostName = host, UserName = user, Password = pwd, VirtualHost = vhost, AutomaticRecoveryEnabled = false };
//					var conn2 = connFac.CreateConnection();
//					var channel2 = conn2.CreateModel();
//					var q = "q." + 0;
//					PublishLegacy(q, channel2, howManyCalls / 4, isWarmUp: true);
//					channel2.Dispose();
//					conn2.Dispose();
//				}
//
//				await WarmupComplete(postWarmupDelay);

                RabbitMQ.Client.IConnection conn    = null;
                RabbitMQ.Client.IModel      channel = null;

                for (int i = 0; i < howManyQueues; i++)
                {
                    var connFac = new RabbitMQ.Client.ConnectionFactory()
                    {
                        HostName = host, UserName = user, Password = pwd, VirtualHost = vhost, AutomaticRecoveryEnabled = false
                    };

                    if (exclusiveConnections || conn == null)
                    {
                        conn    = connFac.CreateConnection();
                        channel = conn.CreateModel();
                    }

                    var q = "q." + i;

                    new Thread(() =>
                    {
                        PublishLegacy(q, channel, howManyCalls, isWarmUp: false);
                    })
                    {
                        IsBackground = true
                    }.Start();
                }
            }
            else
            {
                // Warm up
//				{
//					var conn2 = await RabbitMqNext.ConnectionFactory.Connect(host, vhost, user, pwd, recoverySettings: null, connectionName: "perf_client");
//					var channel2 = await conn2.CreateChannel();
//					var q = "q." + 0;
//					await Task.Delay(1); // Thread switch
//					PublishModern(q, channel2, howManyCalls / 4, isWarmUp: true);
//					await Task.Delay(1); // Thread switch
//					channel2.Dispose();
//					conn2.Dispose();
//				}
//
//				await WarmupComplete(postWarmupDelay);

                RabbitMqNext.IConnection conn    = null;
                RabbitMqNext.IChannel    channel = null;

                for (int i = 0; i < howManyQueues; i++)
                {
                    if (exclusiveConnections || conn == null)
                    {
                        conn = await RabbitMqNext.ConnectionFactory.Connect(host, vhost, user, pwd, recoverySettings : null, connectionName : "perf_client");

                        channel = await conn.CreateChannel();
                    }

                    var q = "q." + i;

                    new Thread(() =>
                    {
                        PublishModern(q, channel, howManyCalls, isWarmUp: false);
                    })
                    {
                        IsBackground = true
                    }.Start();
                }
            }

            _startSync.Set();

            Console.WriteLine("Waiting for publishing to complete");

            for (int i = 0; i < howManyQueues; i++)
            {
                _completionSemaphore.Wait();
            }

            Console.WriteLine("Done\r\n");

            Console.ReadKey();
        }
Esempio n. 30
0
        /// <summary>
        ///
        /// </summary>
        public void customrealpayController()
        {
            try
            {
                ConcurrentQueue <BasicDeliverEventArgs> queue1 = new ConcurrentQueue <BasicDeliverEventArgs>();
                ConnectionFactory factory = new ConnectionFactory();
                factory.UserName = "******";
                factory.Password = "******";
                factory.HostName = "127.0.0.1";
                factory.Port     = 5672;
                factory.AutomaticRecoveryEnabled = true;
                factory.TopologyRecoveryEnabled  = true;


                RabbitMQ.Client.IConnection conn = factory.CreateConnection();
                conn.ConnectionShutdown += (o, e) => {
                };
                IModel channel = conn.CreateModel();
                channel.ExchangeDeclare("customrealpayController", "direct");
                channel.QueueDeclare("customrealpayController", false, false, false, null);
                channel.QueueBind("customrealpayController", "customrealpayController", "customrealpayController", null);

                EventingBasicConsumer c = new EventingBasicConsumer(channel);
                c.Received += (ch, ea) =>
                {
                    queue1.Enqueue(ea);
                };
                string consumerTag = channel.BasicConsume("customrealpayController", false, c);
                Task.Factory.StartNew(() => {
                    BasicDeliverEventArgs bdea = null;
                    while (true)
                    {
                        if (queue1.TryDequeue(out bdea))
                        {
                            try
                            {
                                //Clients.User("*****@*****.**").Send(JsonConvert.DeserializeObject<payExInfo>(Encoding.UTF8.GetString(bdea.Body)));
                                //channel.BasicAck(bdea.DeliveryTag, false);



                                if (dic.Keys.Contains("*****@*****.**"))
                                {
                                    Clients.User("*****@*****.**").Send(JsonConvert.DeserializeObject <payExInfo>(Encoding.UTF8.GetString(bdea.Body)));
                                    channel.BasicAck(bdea.DeliveryTag, false);
                                }
                                else
                                {
                                    channel.BasicAck(bdea.DeliveryTag, true);
                                }
                            }
                            catch (Exception ex)
                            {
                                channel.BasicNack(bdea.DeliveryTag, false, true);
                            }
                        }
                        Thread.Sleep(100);
                    }
                });
            }
            catch (Exception ex)
            {
                customrealpayController();
            }
        }
Esempio n. 31
0
        /// <summary>
        ///
        /// </summary>
        public void Order311FromOMS_GuangZhou()
        {
            try
            {
                ConcurrentQueue <BasicDeliverEventArgs> queue1 = new ConcurrentQueue <BasicDeliverEventArgs>();
                ConnectionFactory factory = new ConnectionFactory();
                factory.UserName = "******";
                factory.Password = "******";
                factory.HostName = "127.0.0.1";
                factory.Port     = 5672;
                factory.AutomaticRecoveryEnabled = true;
                factory.TopologyRecoveryEnabled  = true;


                RabbitMQ.Client.IConnection conn = factory.CreateConnection();
                conn.ConnectionShutdown += (o, e) => {
                };
                IModel channel = conn.CreateModel();
                channel.ExchangeDeclare("ENT311Message_GuangZhou", "direct");
                channel.QueueDeclare("ENT311Message_GuangZhou", false, false, false, null);
                channel.QueueBind("ENT311Message_GuangZhou", "ENT311Message_GuangZhou", "ENT311Message_GuangZhou", null);

                EventingBasicConsumer c = new EventingBasicConsumer(channel);
                c.Received += (ch, ea) =>
                {
                    queue1.Enqueue(ea);
                };
                string consumerTag = channel.BasicConsume("ENT311Message_GuangZhou", false, c);
                Task.Factory.StartNew(() => {
                    BasicDeliverEventArgs bdea = null;
                    while (true)
                    {
                        if (queue1.TryDequeue(out bdea))
                        {
                            try
                            {
                                _ILog4netHelper.WriteLog_Info <MessageHub>(Encoding.UTF8.GetString(bdea.Body), dic.Count.ToString(), null, null);
                                if (dic.Keys.Contains("*****@*****.**"))
                                {
                                    Clients.User("*****@*****.**").Send_Order311_GuangZhou(Encoding.UTF8.GetString(bdea.Body));
                                    //_ILog4netHelper.WriteLog_Info<MessageHub>(re, dic.Count.ToString(), null, null);
                                    channel.BasicAck(bdea.DeliveryTag, false);
                                }
                                else
                                {
                                    channel.BasicNack(bdea.DeliveryTag, false, true);
                                    //channel.BasicAck(bdea.DeliveryTag, true);
                                }
                            }
                            catch (Exception ex)
                            {
                                _ILog4netHelper.WriteLog_Info <MessageHub>(Encoding.UTF8.GetString(bdea.Body), dic.Count.ToString(), null, ex);
                                try
                                {
                                    channel.BasicNack(bdea.DeliveryTag, false, true);
                                }
                                catch (Exception exe)
                                {
                                    //Order311FromOMS_GuangZhou();
                                }
                            }
                        }
                        Thread.Sleep(100);
                    }
                });
            }
            catch (Exception ex)
            {
                Order311FromOMS_GuangZhou();
            }
        }