簡體   English   中英

Rabbitmq消費者成為生產者

[英]rabbitmq consumer becomes a producer

我正在從使用者內的RabbitMQ接收消息。 我必須處理該消息,並將處理后的消息發布到其他隊列中。 我將如何完成?

我的代碼是

using (IConnection connection = factory.CreateConnection())
{
    using (IModel channel = connection.CreateModel())
    {
        if (!String.IsNullOrEmpty(EXCHANGE_NAME))
            channel.ExchangeDeclare(EXCHANGE_NAME, ExchangeType.Direct, durable);

        if (!String.IsNullOrEmpty(QUEUE_NAME))
            channel.QueueDeclare(QUEUE_NAME, false, false, false, null);

        string data = "";
        EventingBasicConsumer consumer = new EventingBasicConsumer();
        consumer.Received += (o, e) =>
        {
            //This is the received message
            data = data + Encoding.ASCII.GetString(e.Body) + Environment.NewLine;
            string processed_data = "processed data = " + data; 
            //I want to write some code here to post the processed message to a different queue.
            //or other idea is "can I use duplex services? 

        };
        string consumerTag = channel.BasicConsume(QUEUE_NAME, true, consumer);

        channel.QueueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY, null);
        channel.QueueUnbind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY, null);
    }
}

底線是您可以共享線程之間的連接,但不能共享通道。 因此,在您的示例中,您可以使用相同的連接,但是當您要發布時,您需要創建一個新的頻道(因為Consumer.Received事件將在另一個線程上引發):

using (IConnection connection = factory.CreateConnection())
{
    using (IModel channel = connection.CreateModel())
    {
        if (!String.IsNullOrEmpty(EXCHANGE_NAME))
            channel.ExchangeDeclare(EXCHANGE_NAME, ExchangeType.Direct, durable);

        if (!String.IsNullOrEmpty(QUEUE_NAME))
            channel.QueueDeclare(QUEUE_NAME, false, false, false, null);

        string data = "";
        EventingBasicConsumer consumer = new EventingBasicConsumer();
        consumer.Received += (o, e) =>
        {
            //This is the received message
            data = data + Encoding.ASCII.GetString(e.Body) + Environment.NewLine;
            string processed_data = "processed data = " + data; 
            //I want to write some code here to post the processed message to a different queue.
            //or other idea is "can I use duplex services? 

            using (IModel channel = connection.CreateModel())
            {
                channel.Publish( ... );
            }

        };
        string consumerTag = channel.BasicConsume(QUEUE_NAME, true, consumer);

        channel.QueueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY, null);
        channel.QueueUnbind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY, null);

        // don't dispose of your channel until you've finished consuming
    }

    // don't dispose of your connection until you've finished consuming
}

確保不要停止消費渠道,直到想要停止消費為止。 連接也是如此。 這是一個常見的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM