[英]How to receive single message from the queue in RabbitMQ using C#
I would like to know how I can receive only one message at a time this is basic code for that我想知道如何一次只接收一条消息这是基本代码
var factory = new ConnectionFactory() { HostName = "localhost" };
var connection = factory.CreateConnection()
var channel = connection.CreateModel()
channel.QueueDeclare("hello", false, false, false, null);
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume("hello", true, consumer);
BasicDeliverEventArgs ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Response.Write(message + " Received.");
If you want wait for 1 message, then keep using channel.BasicConsume
, but leave consumer method after single message. 如果要等待1条消息,则继续使用
channel.BasicConsume
,但在单条消息后保留使用者方法。
If you just get 1 message (if at least 1 exists in queue) then channel.BasicGet
如果您只收到1条消息(如果队列中至少存在1条消息)则为
channel.BasicGet
var data = channel.BasicGet(queueName, true);
PS: PS:
There are nice example on CloudAMQP with .NET: Getting started page. CloudAMQP与.NET有很好的例子:入门页面。
Complementing the last message if you need the text from the message you need to convert: 如果您需要转换消息中的文本,请补充上一条消息:
var data = channel.BasicGet(QueueName, true);
var message = System.Text.Encoding.UTF8.GetString(data.Body);
For other languages if you get an error using the channel.BasicGet
method you can use channel.get
method of the library This was the case with me when i was trying to achieve this using Node.Js对于其他语言,如果您使用
channel.BasicGet
方法出错,您可以使用库的channel.get
方法当我尝试使用 Node.Js 实现此目的时,我就是这种情况
my Node.Js code:我的 Node.Js 代码:
const open = require('amqplib').connect('amqp://admin:password@172.17.0.1:5672?heartbeat:30')
open
.then(conn => conn.createChannel())
.then(async channel => {
console.log('channel created')
const msg = await channel.get('myQueue')
if (msg) {
console.log(msg.content.toString())
channel.ack(msg)
}
})
.catch(console.warn)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.