我试图在同一程序中发布和订阅相同的队列,但是什么也没消耗,我错过了什么吗?
代码:
using System;
using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace CSharpPlayground
{
public static class Program
{
public static void Main()
{
const string queueName = "hello";
var factory = new ConnectionFactory { HostName = "localhost" };
using var connection = factory.CreateConnection();
using var queueDeclareChannel = connection.CreateModel();
queueDeclareChannel.QueueDeclare(
queue: queueName,
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
using var consumerChannel = connection.CreateModel();
var consumer = new AsyncEventingBasicConsumer(consumerChannel);
consumer.Received += async (sender, eventArgs) =>
{
var receivedBody = eventArgs.Body;
var receivedMessage = Encoding.UTF8.GetString(receivedBody.ToArray());
Console.WriteLine($"[x] Received {receivedMessage}");
};
consumerChannel.BasicConsume(
queue: queueName,
autoAck: true,
consumer: consumer);
const string messageToSend = "Hello World!";
var bodyToSend = new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(messageToSend));
var publishChannel = connection.CreateModel();
var basicProperties = publishChannel.CreateBasicProperties();
queueDeclareChannel.BasicPublish(
exchange: "",
routingKey: queueName,
mandatory: false,
basicProperties: basicProperties,
body: bodyToSend);
Console.WriteLine($"[x] Sent {messageToSend}");
Console.ReadKey();
}
}
}
[x] Sent Hello World!
您有一个异步使用者,这意味着您需要告诉ConnectionFactory
您正在以异步方式接收消息。
在DispatchConsumersAsync = true
内部设置new ConnectionFactory {}