Beispiel #1
0
        private static void ReadMessageWithPullModel()
        {
            Console.WriteLine("Reading message from queue. Press 'e' to exit.");

            while (true)
            {
                Console.WriteLine("Tryieng to get a message from the queue...");
                BasicGetResult result = _channel.BasicGet("q1", true);
                if (result != null)
                {
                    var message = Encoding.UTF8.GetString(result.Body.ToArray());
                    Console.WriteLine($"Message: {message}");
                }

                if (Console.KeyAvailable)
                {
                    var kayInfo = Console.ReadKey();
                    if (kayInfo.KeyChar == 'e' || kayInfo.KeyChar == 'E')
                    {
                        return;
                    }
                }

                Thread.Sleep(5000);
            }
        }
Beispiel #2
0
        public static void DirectAcceptExchange()
        {
            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: QueueName);
                    while (true)
                    {
                        BasicGetResult msgResponse = channel.BasicGet(QueueName, true);
                        if (msgResponse != null)
                        {
                            var msgBody = Encoding.UTF8.GetString(msgResponse.Body);
                            Console.WriteLine(string.Format("***接收时间:{0},消息内容:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msgBody));
                        }

                        //BasicGetResult msgResponse2 = channel.BasicGet(QueueName, noAck: false);

                        ////process message ...

                        //channel.BasicAck(msgResponse2.DeliveryTag, multiple: false);
                        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1));
                    }
                }
            }
        }
Beispiel #3
0
        //public bool Receive(out string message) => this.Receive(out message, out string _);

        //public bool Receive(out string message, out string routingKey)
        //{
        //    message = string.Empty;
        //    routingKey = string.Empty;
        //    try
        //    {
        //        BasicGetResult basicGetResult = this.Channel.BasicGet(this.consumerConfigInfo.QueueName, true);
        //        if (basicGetResult == null)
        //        {
        //            Thread.Sleep(500);
        //            return false;
        //        }
        //        byte[] body = basicGetResult.Body.ToArray();
        //        message = CommonLibrary.BinaryDeserialize(body);
        //        routingKey = basicGetResult.RoutingKey;
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        //RecordLog.WriteLog("QueueName:" + this.consumerConfigInfo.QueueName + ",Receive ", "", "", this.consumerConfigInfo.QueueName, ex);
        //        Thread.Sleep(500);
        //        this.Dispose();
        //        return false;
        //    }
        //}

        // public bool ReceiveNeedAck(out string message, out ulong deliveryTag) => this.ReceiveNeedAck(out message, out deliveryTag, out string _);

        public bool ReceiveNeedAck(out string message, out ulong deliveryTag, out string routingKey)
        {
            message     = string.Empty;
            routingKey  = string.Empty;
            deliveryTag = 0UL;
            try
            {
                BasicGetResult basicGetResult = this.Channel.BasicGet(this.consumerConfigInfo.QueueName, false);
                if (basicGetResult == null)
                {
                    Thread.Sleep(500);
                    return(false);
                }
                byte[] body = basicGetResult.Body.ToArray();
                message     = CommonLibrary.BinaryDeserialize(body);
                routingKey  = basicGetResult.RoutingKey;
                deliveryTag = basicGetResult.DeliveryTag;
                return(true);
            }
            catch (Exception ex)
            {
                // RecordLog.WriteLog("QueueName:" + this.consumerConfigInfo.QueueName + ",ReceiveNeedAck", "", "", this.consumerConfigInfo.QueueName, ex);
                Thread.Sleep(500);
                this.Dispose();
                return(false);
            }
        }
Beispiel #4
0
        public void Run()
        {
            Task.Factory.StartNew(() =>
            {
                SqlDb sqlDb = new QT.Entities.Data.SqlDb(@"Data Source=42.112.28.93;Initial Catalog=QT_2;Persist Security Info=True;User ID=wss_price;Password=HzlRt4$$axzG-*UlpuL2gYDu;connection timeout=200");
                QT.Moduls.CrawlerProduct.Cache.CacheProductInfo cacheProductInfo = new QT.Moduls.CrawlerProduct.Cache.CacheProductInfo(sqlDb);

                while (true)
                {
                    BasicGetResult result = this.GetMessage();
                    if (result != null)
                    {
                        string str = System.Text.Encoding.UTF8.GetString(result.Body);
                        if (str != "")
                        {
                            MssRefreshCacheProductInfo job = MssRefreshCacheProductInfo.FromJSON(str);
                            log.Info(string.Format("Get Message For Company:{0} {1}", job.CompanyID, job.Domain));

                            RedisCacheProductInfo rediscacheProductForCompany = RedisCacheProductInfo.Instance();
                            int ProductCache = cacheProductInfo.RefreshAllCacheAllProduct(job.CompanyID);
                            log.Info(string.Format("Company:{0} NumberProductCache:{1}", job.CompanyID, job.Domain));
                        }
                    }
                    this.tokenStop.WaitHandle.WaitOne(10000);
                }
            });
        }
Beispiel #5
0
        // 消费消息-主动获取
        public static void ConsumerGet()
        {
            try
            {
                var factory = RabbitMQConfig.NewConnectionFactory();
                using (var connection = factory.CreateConnection())
                {
                    using (var channel = connection.CreateModel())
                    {
                        //方法中参数prefetchSize为预取的长度,一般设置为0即可,表示长度不限;prefetchCount表示预取的条数,即发送的最大消息条数;global表示是否在Connection中全局设置,true表示Connetion下的所有channel都设置为这个配置
                        channel.BasicQos(prefetchSize: 0, prefetchCount: 2, global: false);
                        channel.ExchangeDeclare(RabbitMQConfig.ExchangeName, RabbitMQConfig.ExchangeType);
                        channel.QueueBind(RabbitMQConfig.QueueName, RabbitMQConfig.ExchangeName, RabbitMQConfig.RoutingKey);
                        channel.QueueDeclare(RabbitMQConfig.QueueName, true, false, false, null);
                        Console.WriteLine("消费者准备就绪....按下任意键获取一个消息");

                        while (true)
                        {
                            Console.ReadKey();
                            BasicGetResult result = channel.BasicGet(RabbitMQConfig.QueueName, true);
                            if (result != null)
                            {
                                var message = Encoding.UTF8.GetString(result.Body);
                                Console.WriteLine($"处理消息【{message}】完成");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Перераспределение сообщений в очередях
        /// </summary>
        /// <param name="queueOf">Название очереди, из которой берутся сообщения</param>
        /// <param name="exchange">Точка распределения</param>
        /// <param name="routingQueueIn">Название маршрутизации очереди, в которую отправляются сообщения</param>
        public void RedistributionQueue(string queueOf, string exchange, string routingQueueIn)
        {
            IModel channel = null;

            try
            {
                channel = ConnectionRabbit.CreateModel();
                while (true)
                {
                    BasicGetResult result = channel.BasicGet(queueOf, false);
                    if (result != null)
                    {
                        channel.BasicPublish(exchange, routingQueueIn, null, result.Body);
                        channel.BasicAck(result.DeliveryTag, false);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch (Exception exception)
            {
                Log.Error(exception.ToString);
                throw new RabbitmqException();
            }
            finally
            {
                if (channel != null)
                {
                    channel.Close();
                }
            }
        }
Beispiel #7
0
        /// <summary>
        /// 响应方主动拉取消息
        /// </summary>
        public static void PullMessage()
        {
            ConnectionFactory factory = new ConnectionFactory();

            factory.Uri = new Uri(RabbitMqSetting.CONNECTIONSTRING);

            using (IConnection connection = factory.CreateConnection())
            {
                using (IModel channel = connection.CreateModel())
                {
                    while (true)
                    {
                        BasicGetResult res = channel.BasicGet(RabbitMqName.Default, true);
                        if (res != null)
                        {
                            Console.WriteLine("receiver:" + UTF8Encoding.UTF8.GetString(res.Body));
                        }
                        else
                        {
                            return;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="exchange">交换器名称</param>
        /// <param name="exchangeType">交换器类型</param>
        /// <param name="queue">队列名称</param>
        /// <param name="key">绑定的键值</param>
        /// <param name="durable">是否持久 true持久,false不持久</param>
        /// <returns></returns>
        public BasicGetResult GetMessage(string exchange, string exchangeType, string queue, string key, bool durable = true)
        {
            BasicGetResult result = null;

            try
            {
                using (var chanl = GetConnect().CreateChanl())
                {
                    var chan = chanl.IChannl;

                    chan.ExchangeDeclare(exchange, exchangeType, durable, false);


                    chan.QueueDeclare(queue, durable, false, false);


                    chan.QueueBind(queue, exchange, key);

                    result = chan.BasicGet(queue, true);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
            }
            return(result);
        }
        /// <summary>
        /// Consumes/Subscribes queue and get published data.
        /// </summary>
        /// <typeparam name="T">Type of consumed object.</typeparam>
        /// <param name="qName">Queue name.</param>
        /// <returns>Returns consumed object result.</returns>
        public T Subscribe <T>(string qName)
        {
            var connectionFactory = new ConnectionFactory();

            _config.GetSection("RabbitMqConnection").Bind(connectionFactory);

            using (var connection = connectionFactory.CreateConnection())
            {
                using (var model = connection.CreateModel())
                {
                    model.QueueDeclare(queue: qName,
                                       durable: true,
                                       exclusive: false,
                                       autoDelete: false,
                                       arguments: null);
                    BasicGetResult consumer = model.BasicGet(qName, true);
                    if (consumer != null)
                    {
                        _body      = Encoding.UTF8.GetString(consumer.Body);
                        _jsonDeser = JsonConvert.DeserializeObject <T>(_body);
                    }
                }
            }

            return((T)_jsonDeser);
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            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, exclusive: false, autoDelete: false, arguments: null); //定义消息队列
                    channel.QueueBind(QueueName, ExchangeName, routingKey: QueueName);                                    //把消息队列绑定到某个交换方式上


                    //持久化消息到队列
                    var props = channel.CreateBasicProperties();
                    props.Persistent = true;
                    string read = "Hello, World!";
                    read = Console.ReadLine();
                    var msgBody = Encoding.UTF8.GetBytes(read);
                    channel.BasicPublish(ExchangeName, routingKey: QueueName, basicProperties: props, body: msgBody);


                    //消费队列中的消息
                    //NoAck:true 告诉RabbitMQ立即从队列中删除消息,
                    //另一个非常受欢迎的方式是从队列中删除已经确认接收的消息,可以通过单独调用BasicAck 进行确认
                    //以下用的是第二种
                    BasicGetResult msgResponse   = channel.BasicGet(QueueName, noAck: false);
                    var            msgBodyReturn = Encoding.UTF8.GetString(msgResponse.Body);
                    Console.WriteLine(msgBodyReturn);
                    //确定之后手动调用删除队列中的消息
                    channel.BasicAck(msgResponse.DeliveryTag, multiple: false);
                }
        }
Beispiel #11
0
        /// <returns>
        /// Uma lista de strings contendo as mensagens da fila.
        /// </returns>
        public List <string> Receive()
        {
            using (IConnection connection = GetConnection())
            {
                using (IModel channel = connection.CreateModel())
                {
                    List <string> list = new List <string>();

                    QueueDeclareOk queueDeclareResponse = channel.QueueDeclare(this._queue, false, false, false, null);

                    //Fila vazia
                    if (queueDeclareResponse.MessageCount == 0)
                    {
                        return(list);
                    }

                    uint queueDeep;

                    do
                    {
                        BasicGetResult result = channel.BasicGet(this._queue, true);
                        if (result == null)
                        {
                            return(null);
                        }
                        queueDeep = result.MessageCount;
                        string message = Encoding.UTF8.GetString(result.Body.ToArray());
                        list.Add(message);
                    } while (queueDeep != 0);

                    return(list);
                }
            }
        }
Beispiel #12
0
        public TMessage GetMessage <TMessage>(ISerializationStrategy serializationStrategy, bool retry)
            where TMessage : class
        {
            TMessage message = default(TMessage);

            if (!retry)
            {
                Console.WriteLine("Getting message ...");
                BasicGetResult args = _channel.BasicGet(_queueName, true);
                if (args != null)
                {
                    message = new BinarySerializationStrategy().Deserialize <TMessage>(args.Body);
                }
                return(message);
            }

            new Action(() =>
            {
                try
                {
                    var consumer = new QueueingBasicConsumer(_channel);
                    Console.WriteLine("Consuming messages ...");
                    _channel.BasicConsume(_queueName, true, "", null, consumer);
                    var args = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                    message  = serializationStrategy.Deserialize <TMessage>(args.Body);
                }
                catch (EndOfStreamException)
                {
                }
            }).Background().BlockUntil(() => message != null)();

            return(message);
        }
Beispiel #13
0
        public Consumer(string queueName)
        {
            _rabbitMQService = new RabbitMQService();
            while (true)
            {
                using (var connection = _rabbitMQService.GetRabbitMQConnection())
                {
                    using (var channel = connection.CreateModel())
                    {
                        channel.QueueDeclare(queueName, false, false, false, null);
                        var consumer = new EventingBasicConsumer(channel);
                        BasicGetResult result = channel.BasicGet(queueName, true);
                        if (result != null)
                        {
                            string data =
                            Encoding.UTF8.GetString(result.Body);

                            Mail.Mail mail = new Mail.Mail();

                            mail.SendMail(data);

                            Console.WriteLine(data);
                        }
                    }
                }
            }
        }
Beispiel #14
0
        private void LoopGetMessage(ConnectionFactory factory, string exchangeName, string queueName, string routtingKey)
        {
            var connection = factory.CreateConnection();

            _channel = connection.CreateModel();

            _channel.ExchangeDeclare(exchangeName, EnumRabbitExchangeType.topic.ToString(), durable: true, autoDelete: false, arguments: null);
            _channel.QueueDeclare(queueName, durable: true, autoDelete: false, exclusive: false, arguments: null);
            _channel.QueueBind(queueName, exchangeName, routingKey: routtingKey);
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    BasicGetResult msgResponse = _channel.BasicGet(queueName, autoAck: true);
                    if (msgResponse != null)
                    {
                        var msgBody = Encoding.UTF8.GetString(msgResponse.Body);
                        BeginInvoke(new Action(() => { Rtx_SendContext.Text = "\r" + string.Format("***接收时间:{0},消息内容:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msgBody); }));
                    }

                    //BasicGetResult msgResponse2 = channel.BasicGet(QueueName, noAck: false);

                    ////process message ...

                    //channel.BasicAck(msgResponse2.DeliveryTag, multiple: false);
                    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1));
                }
            });
        }
 /// <summary>
 /// Fetch next 1 incoming message in queue and dispatch if event handler is associated with it.
 /// </summary>
 public void Fetch()
 {
     lock (_modelLock)
     {
         try
         {
             while (true)
             {
                 BasicGetResult message = _model.BasicGet(_rmqQueueName, false);
                 if (message == null)
                 {
                     return;
                 }
                 else
                 {
                     Dispatch(message.RoutingKey, GetMessageHeader(message), message.Body.Span.ToArray(), message.DeliveryTag);
                 }
             }
         }
         catch (Exception e)
         {
             LastErrorMessage = e.Message;
         }
     }
 }
        //This method is written to consume only one message at a time.
        public void Consume(object sender, EventArgs e)
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost"
            };                                                               // Creates ConnectionFactory.

            //This is a "using" statement, and not an import.
            //Here, is serves to automatically close the connection and the channel once is leave the block.
            //Basically, is will automatically run channel.Close(), and connection.Close()
            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    // Gets a single message from the queue without acknowledging.
                    BasicGetResult result = channel.BasicGet(queue: "hello", autoAck: false);

                    if (result == null)// Checks if the queue is empty.
                    {
                        Console.WriteLine("No messages avaliable at this time.");
                    }
                    else
                    {
                        IBasicProperties props   = result.BasicProperties;        // Collects message properties.
                        byte[]           body    = result.Body;                   // Collects message body.
                        string           message = Encoding.UTF8.GetString(body); // Converts body from bytes to string.
                        channel.BasicAck(result.DeliveryTag, false);              // Manually sends acknowledgement for message.
                        Console.WriteLine("Received {0}", message);               // Prints message to console.
                        rabbitMQViewModel.Message = "Consumed " + message;        // Displays what was received in label in the UI.
                    }
                }
        }
Beispiel #17
0
        public static string Recieved()
        {
            string resultData;
            var    connectionFactory = new ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var connection = connectionFactory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare("notification", true, false, false, null);
                    var            consumer = new EventingBasicConsumer(channel);
                    BasicGetResult result   = channel.BasicGet("notification", true);
                    try
                    {
                        resultData = Encoding.UTF8.GetString(result.Body);
                    }
                    catch
                    {
                        resultData = "No message";
                    }
                }
            }
            Console.WriteLine(resultData);
            return(resultData);
        }
Beispiel #18
0
        private StockRespons ReceiveMessage()
        {
            string AllQueueName = "Test_Queue";
            string ExchangeName = "Topic_Exchange";

            ConnectionFactory _factory = new ConnectionFactory {
                HostName = "localhost", UserName = "******", Password = "******"
            };
            IConnection _connection;

            using (_connection = _factory.CreateConnection())
            {
                using (var channel = _connection.CreateModel())
                {
                    // Create and declare queue
                    channel.ExchangeDeclare(ExchangeName, "topic");
                    channel.QueueDeclare(AllQueueName, true, false, false, null);
                    channel.QueueBind(AllQueueName, ExchangeName, "stock.test");
                    BasicGetResult status = channel.BasicGet(AllQueueName, false);

                    Subscription subscription = new Subscription(channel, AllQueueName, true);

                    // Read from queue
                    BasicDeliverEventArgs deliveryArguments = subscription.Next();
                    var body    = deliveryArguments.Body;
                    var message = Encoding.UTF8.GetString(body);
                    var stock   = JsonConvert.DeserializeObject <StockRespons>(message);
                    subscription.Ack(deliveryArguments);
                    _connection.Close();
                    return(stock);
                }
            }
        }
Beispiel #19
0
        /// <summary>
        /// 获取单条消息
        /// </summary>
        /// <param name="basicGetMethod">回调函数</param>
        /// <param name="data">传过来,再传回去</param>
        public void BasicGet(ReceiveMessageDelegate <Tuple <bool, string, Dictionary <string, object> > > basicGetMethod, Dictionary <string, object> data = null)
        {
            try
            {
                using (var channel = this.GetConnection().CreateModel())
                {
                    BasicGetResult res = channel.BasicGet(RabbitConfig.QueueName, false);
                    if (res != null)
                    {
                        //普通使用方式BasicGet
                        //noAck = true,不需要回复,接收到消息后,queue上的消息就会清除
                        //noAck = false,需要回复,接收到消息后,queue上的消息不会被清除,直到调用channel.basicAck(deliveryTag, false); queue上的消息才会被清除 而且,在当前连接断开以前,其它客户端将不能收到此queue上的消息

                        IBasicProperties props = res.BasicProperties;
                        bool             t     = res.Redelivered;
                        t = true;
                        string result = Encoding.UTF8.GetString(res.Body);
                        channel.BasicAck(res.DeliveryTag, false);
                        basicGetMethod(new Tuple <bool, string, Dictionary <string, object> >(true, result, data));
                    }
                    else
                    {
                        basicGetMethod(new Tuple <bool, string, Dictionary <string, object> >(false, "未找到所需数据", data));
                    }
                }
            }
            catch (Exception ex)
            {
                //  mqErrCnt++;
                LogCom.WriteExceptToFile(ex, "RabbitMQHelper.BasicGet");
            }
        }
Beispiel #20
0
        public void ReceiveMessage()
        {
            using (_connection = _factory.CreateConnection())
            {
                using (var channel = _connection.CreateModel())
                {
                    // create and declare queue
                    channel.ExchangeDeclare(ExchangeName, "topic");
                    channel.QueueDeclare(AllQueueName, true, false, false, null);
                    channel.QueueBind(AllQueueName, ExchangeName, "stock.patch");
                    BasicGetResult status = channel.BasicGet(AllQueueName, false);

                    //channel.BasicQos(0, 10, false);
                    Subscription subscription = new Subscription(channel, AllQueueName, false);

                    //read from queue until no messages left

                    while (true)
                    {
                        BasicDeliverEventArgs deliveryArguments = subscription.Next();

                        var body    = deliveryArguments.Body;
                        var message = Encoding.UTF8.GetString(body);
                        var stock   = JsonConvert.DeserializeObject <StockRespons>(message);

                        subscription.Ack(deliveryArguments);

                        // perform operation
                        ConsumeMessage(stock);
                    }
                }
            }
        }
Beispiel #21
0
        public string receive(IConnection con, string myqueue)
        {
            try
            {
                string queue   = myqueue;
                var    stock   = new Stock();
                IModel channel = con.CreateModel();
                channel.QueueDeclare(queue: queue, durable: true, exclusive: false, autoDelete: false, arguments: null);
                var            consumer = new EventingBasicConsumer(channel);
                BasicGetResult result   = channel.BasicGet(queue: queue, autoAck: true);
                if (result != null)
                {
                    var msg = Encoding.UTF8.GetString(result.Body);
                    //var stockCode = BotService.GetStockCode(msg);

                    return(msg);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
Beispiel #22
0
        public List <T> Recive <T>(string key, bool read = true)
        {
            var res = new List <T>();

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    var queueDeclareOK = channel.QueueDeclarePassive(key);
                    var consumerCount  = queueDeclareOK.MessageCount;

                    string         resultStr = null;
                    BasicGetResult result    = null;
                    for (int i = 0; i < consumerCount; i++)
                    {
                        result = channel.BasicGet(key, false);

                        if (result != null)
                        {
                            resultStr = Encoding.UTF8.GetString(result.Body);
                            res.Add(JsonConvert.DeserializeObject <T>(resultStr));
                        }
                    }

                    if (read)
                    {
                        channel.BasicAck(result.DeliveryTag, false);
                    }
                }

            return(res);
        }
        public IEnumerable <string> Ler()
        {
            try
            {
                List <string> dadosRecebidos = new List <string>();

                using (var _channel = _connectionFactory.CreateConnection().CreateModel())
                {
                    BasicGetResult result = _channel.BasicGet(_configuration.GetValue <string>("RabbitMQ:Fila"), false);

                    while (result != null)
                    {
                        dadosRecebidos.Add(Encoding.UTF8.GetString(result.Body));

                        _channel.BasicAck(result.DeliveryTag, false);

                        result = _channel.BasicGet(_configuration.GetValue <string>("RabbitMQ:Fila"), false);
                    }
                }

                return(dadosRecebidos);
            }
            catch (Exception ex)
            {
                _elasticService.Logar(_configuration.GetValue <string>("RabbitMQ:Logs:Aplicacao:BaseUrl"), _configuration.GetValue <string>("RabbitMQ:Logs:Aplicacao:Index"),
                                      JsonConvert.SerializeObject(new ObjetoLog("Erro ao realizar leitura dos processos", ex.Message)));

                return(default);
Beispiel #24
0
        List <BasicGetResult> ReceiveMessages(string queue)
        {
            var factory = new ConnectionFactory()
            {
                HostName = ServiceConfigurationSection.Instance.RabbitMQ_HostName
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    var result = new List <BasicGetResult>();
                    channel.QueueDeclare(queue: queue, durable: false, exclusive: false, autoDelete: false, arguments: null);

                    BasicGetResult basicGet = null;
                    do
                    {
                        basicGet = channel.BasicGet(queue, true);
                        if (basicGet != null)
                        {
                            result.Add(basicGet);
                        }
                    }while (basicGet != null);

                    return(result);
                }
        }
Beispiel #25
0
            public void Receive(string queueName)
            {
                try {
                    using (Connection())
                    {
                        if (connection != null)
                        {
                            using (IModel channel = connection.CreateModel())
                            {
                                channel.QueueDeclare(queue: queueName,
                                                     durable: false,
                                                     exclusive: false,
                                                     autoDelete: false,
                                                     arguments: null);

                                BasicGetResult result = channel.BasicGet(queueName, true);
                                if (result != null)
                                {
                                    string data = Encoding.UTF8.GetString(result.Body);
                                    //testing remove later
                                    Console.WriteLine(data);
                                }
                            }
                        }
                    }
                }
                catch (BrokerUnreachableException)
                {
                    Console.WriteLine("Unable to connect, enter either a correct HostName, UserName and/or Password.");
                    throw;
                }
                Disconnect();
            }
Beispiel #26
0
    public T Revice <T>(string key)
    {
        using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                var queueDeclareOK = channel.QueueDeclarePassive(key);
                var consumerCount  = queueDeclareOK.MessageCount;

                string         resultStr = null;
                BasicGetResult result    = null;
                for (int i = 0; i < 1; i++)
                {
                    result = channel.BasicGet(key, false);

                    if (result == null)
                    {
                        Console.Write("// No message");
                    }
                    else
                    {
                        resultStr = Encoding.UTF8.GetString(result.Body);
                    }
                }

                channel.BasicAck(result.DeliveryTag, false);
                return(JsonConvert.DeserializeObject <T>(resultStr));
            }
    }
 public TMessage ExecuteRetrievalOfSingleMessage()
 {
     try
     {
         ConnectionFactory connectionFactory = CreateConnectionFactory();
         using (IConnection connection = connectionFactory.CreateConnection())
         {
             using (IModel channel = connection.CreateModel())
             {
                 channel.QueueDeclare(_queueName, false, false, false, null);
                 BasicGetResult result = channel.BasicGet(_queueName, false);
                 if (result != null)
                 {
                     byte[] bodyDataByteArray = result.Body;
                     _message = ByteArrayToObject(bodyDataByteArray);
                     channel.BasicAck(result.DeliveryTag, false);
                 }
             }
         }
         return(_message as TMessage);
     }
     catch (Exception exception)
     {
         //
     }
     return(null);
 }
Beispiel #28
0
        public async Task Setup()
        {
            var connectionFactory = _host.Settings.GetConnectionFactory();

            using (var connection = connectionFactory.CreateConnection())
                using (var model = connection.CreateModel())
                {
                    var log = Logging.Logger.Get("UnitTest");

                    log.Debug("Sending empty message");

                    model.BasicPublish("input_queue", "", model.CreateBasicProperties(), null);

                    await Task.Delay(5000).ConfigureAwait(false);

                    log.Debug("Reading error message");

                    _basicGetResult = model.BasicGet("input_queue_error", true);

                    _body = Encoding.UTF8.GetString(_basicGetResult.Body);

                    model.Close(200, "Cleanup complete");
                    connection.Close(200, "Cleanup complete");
                }
        }
Beispiel #29
0
        private static void Consume(ConnectionFactory factory, IConnection conn)
        {
            //The IConnection interface can then be used to open a channel:
            IModel channel = conn.CreateModel();

            // To retrieve individual messages, use IModel.BasicGet. The returned value
            // is an instance of BasicGetResult, from which the header information (properties) and
            // message body can be extracted:
            bool           noAck  = false;
            BasicGetResult result = channel.BasicGet(queueName, noAck);

            if (result == null)
            {
                // No message available at this time.
                Console.WriteLine("No message available at this time.");
            }
            else
            {
                IBasicProperties props = result.BasicProperties;
                byte[]           body  = result.Body;
                string           msg   = System.Text.Encoding.UTF8.GetString(body);

                Console.WriteLine("Message.Length:" + body.Length);
                Console.WriteLine("Message:" + msg);

                //Since noAck = false above, you must also call IModel.BasicAck to
                //acknowledge that you have successfully received and processed the message:
                channel.BasicAck(result.DeliveryTag, false);
            }
        }
Beispiel #30
0
        /// <summary>
        /// 从消息队列中接收消息,主动获取模式
        /// </summary>
        public static List <string> ReceiveLstMsg(string queueName)
        {
            List <string> lstMsg = new List <string>();

            try
            {
                using (var connection = factoryMQ.CreateConnection())
                {
                    using (var channel = connection.CreateModel())
                    {
                        channel.QueueDeclare(queueName, false, false, false, null);
                        while (true)
                        {
                            BasicGetResult res = channel.BasicGet(queueName, true);
                            if (res != null)
                            {
                                string message = System.Text.UTF8Encoding.UTF8.GetString(res.Body);
                                lstMsg.Add(message);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception se)
            {
                logger.Error("接受消息失败,主动获取模式", se);
                return(null);
            }
            return(lstMsg);
        }