RabbitMQ + .NET C#:从未在同一程序中使用已发布的消息,为什么?

问题描述 投票:0回答:1

我试图在同一程序中发布和订阅相同的队列,但是什么也没消耗,我错过了什么吗?

代码:

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!
c# .net .net-core rabbitmq
1个回答
0
投票

您有一个异步使用者,这意味着您需要告诉ConnectionFactory您正在以异步方式接收消息。

DispatchConsumersAsync = true内部设置new ConnectionFactory {}

© www.soinside.com 2019 - 2024. All rights reserved.