[英]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.