Example #1
0
        private void GenericSubscriptionQueue_MessageReceived
            (RabbitMQ.Client.IBasicConsumer sender, RabbitMQ.Client.Events.BasicDeliverEventArgs args)
        {
            RabbitMQ.Client.Events.EventingBasicConsumer consumer = (RabbitMQ.Client.Events.EventingBasicConsumer)sender;

            try {
                // don't reprocess items that have been processed
                if (genericSubscriptionQueue.GetLastProcessedUndelivered() != args.DeliveryTag)
                {
                    BaseNotification notification = NotificationExtension.Deserialize(Encoding.ASCII.GetString(args.Body));

                    eventLogRepository.WriteInformationLog("Processing notification type: {NotificationType}. Data: {QueueMessage}".Inject(new { QueueMessage = notification.ToJson(), NotificationType = notification.NotificationType.ToString() }));

                    var handler = notificationHandlerFactory(notification.NotificationType); // autofac will get the right handler
                    handler.ProcessNotification(notification);

                    // Always clear the context at the end of a transaction
                    _uow.ClearContext();
                }

                genericSubscriptionQueue.Ack(consumer, args.DeliveryTag);
            } catch (QueueDataError <string> serializationEx)  {
                eventLogRepository.WriteErrorLog("Serializing problem with notification.", serializationEx);
            } catch (QueueDataError <BaseNotification> notificationEx) {
                eventLogRepository.WriteErrorLog("Error processing notification.", notificationEx);

                PublishToQueue(notificationEx.ProcessingObject, Configuration.RabbitMQNotificationErrorQueue);
            } catch (Exception ex) {
                eventLogRepository.WriteErrorLog("Unhandled error processing notification.", ex);
            }
        }
        private void GenericSubscriptionQueue_MessageReceived
            (RabbitMQ.Client.IBasicConsumer sender, RabbitMQ.Client.Events.BasicDeliverEventArgs args)
        {
            RabbitMQ.Client.Events.EventingBasicConsumer consumer = (RabbitMQ.Client.Events.EventingBasicConsumer)sender;

            try
            {
                // don't reprocess items that have been processed
                if (_genericSubscriptionQueue.GetLastProcessedUndelivered() != args.DeliveryTag)
                {
                    string rawOrder = Encoding.ASCII.GetString(args.Body);

                    ProcessOrder(rawOrder);
                }

                _genericSubscriptionQueue.Ack(consumer, args.DeliveryTag);
            }
            catch (QueueDataError <string> serializationEx)
            {
                _log.WriteErrorLog("Serializing problem with order update.", serializationEx);
            }
            catch (Exception ex)
            {
                _log.WriteErrorLog("Unhandled error processing order update.", ex);
            }
        }
Example #3
0
 public void SetListenerCallback(ReadQueueHandler callback)
 {
     consumer                   = thisExch.CreateConsumer();
     consumer.Received         += LocalCallback;
     SubscribedMessageReceived += callback;
     thisExch.channel.BasicConsume(thisConnDetail.queueName, true, consumer);
 }
Example #4
0
        private void SubscriptionQueue_MessageReceived(object sender, RabbitMQ.Client.Events.BasicDeliverEventArgs args)
        {
            RabbitMQ.Client.Events.EventingBasicConsumer consumer = (RabbitMQ.Client.Events.EventingBasicConsumer)sender;

            try {
                ConfirmationFile confirmation = DeserializeConfirmation(args.Body);

                ProcessIncomingConfirmation(confirmation);

                //Try to save the confirmation 5 times. Several threads are modifying the order history table, so there are occasional concurrency errors.
                KeithLink.Svc.Impl.Helpers.Retry.Do(() => _conversionLogic.SaveConfirmationAsOrderHistory(confirmation), TimeSpan.FromSeconds(1), 5);

                genericSubscriptionQueue.Ack(consumer, args.DeliveryTag);
            }
            catch (QueueDataError <ConfirmationFile> dataException) {
                // Move to errror queue
                PublishToQueue(dataException.ProcessingObject, ConfirmationQueueLocation.Error);
                _log.WriteErrorLog(dataException.Message);
            }
            catch (Exception ex) {
                // Send NACK
                _log.WriteErrorLog("Error processing confirmation.", ex);
                genericSubscriptionQueue.Nack(consumer, args.DeliveryTag);
            }
        }
Example #5
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
Example #6
0
        private void BaseInit(ConnectionDetail cd)
        {
            thisConnDetail = cd.Copy();
            if (thisConnDetail.queueName == "")
            {
                thisConnDetail = thisConnDetail.UpdateQueueDetail(System.Guid.NewGuid().ToString(), null);
            }

            messagesSent   = 0;
            consumer       = null;
            clientCallback = null;
        }
Example #7
0
 public int Recv(ref string str)
 {
     using (IModel channel = connection.CreateModel())
     {
         channel.QueueDeclare(queue, false, false, false, null);
         var            consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(channel);
         BasicGetResult result   = channel.BasicGet(queue, true);
         if (result != null)
         {
             str = Encoding.UTF8.GetString(result.Body);
         }
     }
     return(str.Length);
 }
Example #8
0
        public void Receive()
        {
            var channel      = this.ConnectionPool.GetChannel().Channel;
            var queueDeclare = channel.QueueDeclare("hello", false, false, false, null);

            channel.BasicQos(0, 1, false);
            var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(channel);

            consumer.Received += (sender, ea) =>
            {
                var message = Encoding.UTF8.GetString(ea.Body);
                Console.WriteLine("[x] Received {0}", message);
                channel.BasicAck(ea.DeliveryTag, false);
            };
            channel.BasicConsume(queueDeclare.QueueName, false, consumer);
        }
Example #9
0
        static void Main(string[] args)
        {
            var exchange           = "consumerModeExchange";
            var eventConsumerQueue = "eventConsumerQueue";

            // Create factory
            var factory = new ConnectionFactory
            {
                HostName = "127.0.0.1",
                UserName = "******",
                Password = "******"
            };

            // Create connection
            var connection = factory.CreateConnection();

            // Create channel
            var channel = connection.CreateModel();

            // Declare exchange
            channel.ExchangeDeclare(exchange, ExchangeType.Direct, true, false, null);

            // Declare queue
            channel.QueueDeclare(eventConsumerQueue, true, false, false, null);

            // Bind queue
            channel.QueueBind(eventConsumerQueue, exchange, "", null);

            // Set Qos, narrowing the channel allow the consumer to consume the msg, the msg will not lose
            channel.BasicQos(0, 1, false);

            // Create consumer
            var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(channel);

            consumer.Received += (sender, e) =>
            {
                var msg = Encoding.UTF8.GetString(e.Body);
                Console.WriteLine(msg);
                Thread.Sleep(1000 * 1);

                channel.BasicAck(e.DeliveryTag, false);
            };

            channel.BasicConsume(eventConsumerQueue, false, consumer);
            Console.Read();
        }
        public IConnection Consume(string queueName, Action <string> act)
        {
            var connection = this.GetRabbitMQConnection();
            var channel    = connection.CreateModel();

            channel.QueueDeclare(queueName, true, false, false, null);
            var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(channel);

            consumer.Received += (model, ea) =>
            {
                var _body    = ea.Body.ToArray();
                var _message = Encoding.UTF8.GetString(_body);//serialized string

                act(_message);

                channel.BasicAck(ea.DeliveryTag, false);
            };
            channel.BasicConsume(queue: queueName,
                                 autoAck: false,
                                 consumer: consumer);

            return(connection);
        }
Example #11
0
        static void Receive()
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);

                    var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(channel);
                    consumer.Received += (model, ea) =>
                    {
                        var body    = ea.Body;
                        var message = Encoding.UTF8.GetString(body);
                        Console.WriteLine(" [x] Received {0}", message);
                    };
                    channel.BasicConsume(queue: "hello", autoAck: true, consumer: consumer);
                }
            Thread.Sleep(1000);
        }
Example #12
0
        private void GenericSubscriptionQueue_MessageReceived
            (RabbitMQ.Client.IBasicConsumer sender, RabbitMQ.Client.Events.BasicDeliverEventArgs args)
        {
            RabbitMQ.Client.Events.EventingBasicConsumer consumer = (RabbitMQ.Client.Events.EventingBasicConsumer)sender;

            try
            {
                // don't reprocess items that have been processed
                if (_genericSubscriptionQueue.GetLastProcessedUndelivered() != args.DeliveryTag)
                {
                    string msg = Encoding.ASCII.GetString(args.Body);

                    PushMessage pushmessage = JsonConvert.DeserializeObject <PushMessage>(msg);

                    _eventLogRepository.WriteInformationLog
                        ("Processing push message from queue. Notification: {QueueMessage}".InjectSingleValue
                            ("QueueMessage", msg));

                    ProcessIncomingPushMessage(pushmessage);
                }

                _genericSubscriptionQueue.Ack(consumer, args.DeliveryTag);
            }
            catch (QueueDataError <string> serializationEx)
            {
                _eventLogRepository.WriteErrorLog("Serializing problem with push message.", serializationEx);
            }
            catch (QueueDataError <BaseNotification> notificationEx)
            {
                _eventLogRepository.WriteErrorLog("Error processing push message.", notificationEx);
            }
            catch (Exception ex)
            {
                _eventLogRepository.WriteErrorLog("Unhandled error processing push message.", ex);
            }
        }
Example #13
0
        /// <summary>
        /// RabbitMQ发送消息
        /// </summary>
        /// <param name="queuqname">具体入队的队列名称</param>
        /// <returns></returns>
        public static void ReceiveMsg(string queuqname, ushort limitnum = 3)
        {
            #region 处理方法
            try
            {
                #region 构建消息队列
                //1.实例化连接工厂
                var factory = new RabbitMQ.Client.ConnectionFactory();
                factory.HostName = RabbitMQ_Host;
                factory.UserName = RabbitMQ_User;
                factory.Password = RabbitMQ_Pwd;
                factory.AutomaticRecoveryEnabled = true;
                //2. 建立连接
                var connection = factory.CreateConnection();
                //3. 创建信道
                var channel = connection.CreateModel();

                var  queue_name = queuqname; //项目下游上传的队列信息
                bool durable    = true;      //队列是否持久化
                bool exclusive  = false;
                bool autoDelete = false;     //设置 autoDeleted=true 的队列,当没有消费者之后,队列会自动被删除
                                             //4. 申明队列
                channel.QueueDeclare(queue_name, durable, exclusive, autoDelete, null);
                //5. 构造消费者实例
                var  consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(channel);
                bool autoAck  = false;
                //autoAck:true;自动进行消息确认,当消费端接收到消息后,就自动发送ack信号,不管消息是否正确处理完毕
                //autoAck:false;关闭自动消息确认,通过调用BasicAck方法手动进行消息确认
                //6. 绑定消息接收后的事件委托

                //8. 启动消费者
                //设置prefetchCount : 3 来告知RabbitMQ,在未收到消费端的N条消息确认时,不再分发消息,也就确保了当消费端处于忙碌状态时
                channel.BasicQos(0, limitnum, false);

                channel.BasicConsume(queue_name, autoAck, consumer);

                #endregion

                #region 队列-接收消息的处理方法
                consumer.Received += (model, ea) =>
                {
                    try
                    {
                        //var body = ea.Body.ToArray();
                        var message = Encoding.UTF8.GetString(ea.Body.ToArray());
                        //获取消息后进行操作,do something
                        bool flag = false;
                        if (!string.IsNullOrEmpty(message))
                        {
                            try
                            {
                                //做其他存储或处理操作
                                //JMB_ServiceClass.Model.MSQSModel.MessageQueueModel.MessageQueueDataModel datamodel = Newtonsoft.Json.JsonConvert.DeserializeObject<JMB_ServiceClass.Model.MSQSModel.MessageQueueModel.MessageQueueDataModel>(message);
                                //if (datamodel.datatype == 1)
                                //{
                                //pub.ConnError_TestSysShow("RabbitMq-Item", "Item-Attence", "解析data成功。model参数:" + datamodel.jsondata);

                                //考勤数据,则
                                //JMB_ServiceClass.Model.NormalModel.ItemModule.AttenceModel.AttenceInsertQueueAllInfo mod = Newtonsoft.Json.JsonConvert.DeserializeObject<JMB_ServiceClass.Model.NormalModel.ItemModule.AttenceModel.AttenceInsertQueueAllInfo>(datamodel.jsondata);

                                //JMB_ServiceClass.Dal.NormalDal.Attence dal = new JMB_ServiceClass.Dal.NormalDal.Attence();
                                // flag = dal.Queue_ProjectQueue_Attence(mod);

                                //pub.ConnError_TestSysShow("RabbitMq-Item", "Item-Attence", "项目下游请求数据-处理成功,flag:" + flag + ",model参数:" + datamodel.jsondata);
                                //    }
                            }
                            catch (Exception ex)
                            {
                                //    //pub.ConnError("RabbitMQ", "Event_RabbitMQ_Method1", "项目下游请求数据-处理Message数据时,发生异常----" + ex.Message);
                                //    //pub.ConnError_TestSysShow("RabbitMq-RST", "Item-Attence", "项目下游请求数据-处理Message数据时,发生异常原数据message=" + message);
                            }
                        }
                        else
                        {
                            flag = true;
                        }
                        if (flag)
                        {
                            //操作完毕,则手动确认消息可删除
                            // 7. 发送消息确认信号(手动消息确认)
                            channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                        }
                    }
                    catch (Exception ex)
                    {
                        //JMB_ServiceClass.Common.pub.ConnError("RabbitMQ", "Event_RabbitMQ_Method1", "项目下游请求数据-接收数据后-发生异常:" + ex.Message);
                    }
                };
                #endregion

                //JMB_ServiceClass.Common.pub.ConnError("RabbitMQ", "Event_RabbitMQ_Method1", "项目下游请求数据-RabbitMQ监听消息启动成功");
            }
            catch (Exception ex)
            {
                //JMB_ServiceClass.Common.pub.ConnError("RabbitMQ", "Event_RabbitMQ_Method1", "项目下游请求数据-构建rabbitmq的queue异常:" + ex.Message);
                //RabbitMQ_Event1_IsRuning = false;
                //RabbitMQ_Event1_checkDate = DateTime.Now;
                //JMB_ServiceClass.Common.pub.ConnError("RabbitMQ", "Event_RabbitMQ_Method1", "项目下游请求数据-RabbitMQ监听消息——已关闭");
            }
            //finally
            //{
            //    connection.Close();//不能关,关了就停止接收消息了
            //    channel.Close();
            //}
            #endregion
        }
Example #14
0
        public static void Main()
        {
            try
            {
                var factory =
                    new RabbitMQ.Client.ConnectionFactory
                {
                    Port     = 5672,
                    UserName = "******",
                    Password = "******",
                    HostName = "localhost",
                };

                //var factory =
                //	new RabbitMQ.Client.ConnectionFactory
                //	{
                //		Uri = new System.Uri(uriString: "amqp://*****:*****@localhost:5672"),
                //	};

                string queueName    = "TestQueue";
                string exchangeName = string.Empty;

                using (var connection = factory.CreateConnection())
                {
                    using (var channel = connection.CreateModel())
                    {
                        channel.QueueDeclare
                            (queue: queueName,
                            durable: true,
                            exclusive: false,
                            autoDelete: false,
                            arguments: null);

                        var consumer =
                            new RabbitMQ.Client.Events.EventingBasicConsumer(model: channel);

                        consumer.Received += (sender, e) =>
                        {
                            byte[] body = e.Body.ToArray();

                            string message =
                                System.Text.Encoding.UTF8.GetString(body);

                            System.Console.WriteLine($"Message [{ message }] Received...");
                        };

                        //channel.BasicConsume
                        //	(queue: queueName,
                        //	autoAck: true,
                        //	consumerTag: string.Empty, // null -> Runtime Error!
                        //	noLocal: false,
                        //	exclusive: false,
                        //	arguments: null,
                        //	consumer: consumer);

                        // using RabbitMQ.Client;
                        channel.BasicConsume
                            (queue: queueName,
                            autoAck: true,
                            consumer: consumer);

                        // به محل قرارگیری دو دستور ذیل، بر خلاف پروژه قبلی توجه نمایید
                        System.Console.WriteLine("Press [ENTER] to exit the Consumer (Receiver) App...");
                        System.Console.ReadLine();
                    }
                }
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);

                System.Console.Write("Press [ENTER] to exit the Consumer (Receiver) App...");
                System.Console.ReadLine();
            }
        }