首页 > 解决方案 > 无法使用 Masstransit 读取队列消息

问题描述

我有一个包含一些消息的队列(使用公共交通创建)。

我尝试了这段代码来获取消息(见下文)。

我希望在 Console.Out 行上收到消息,但我从未打过这一行,消息仍在队列中。我没有收到任何错误。

任何想法 ?

 class Program
    {
        static void Main(string[] args)
        {
            var bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
    
                cfg.Host("localhost", "/", h =>
                {
                    h.Username("guest");
                    h.Password("guest");
                });
    
                cfg.ReceiveEndpoint("myQueue", e =>
                {
                    e.Handler<ProcessingQueue>(context =>
                    {
                        return Console.Out.WriteLineAsync($"{context.Message.Id}");
                    });
    
                });
    
            });
        }
    }
    
    public class ProcessingQueue
    {
        public int Id { get; set; }
    
        public string Name { get; set; }
    }

谢谢,

我试图添加:

bus.Start();
Console.WriteLine("Receive listening for messages");
Console.ReadLine();
bus.Stop();

但是当我这样做时,会myQueue_skipped创建一个包含我的消息的新队列。

标签: c#.netrabbitmqmessage-queuemasstransit

解决方案


尝试将此代码用于 ReceiveEndpoint

cfg.ReceiveEndpoint("myQueue", e =>
{
    e.Consumer<MessagesConsumer>();
});

“MessagesConsumer”必须从 IConsumer 继承

public class MessagesConsumer: IConsumer<ProcessingQueue>      
{   public async Task Consume(ConsumeContext<ProcessingQueue> context)
        {
             //access to the properties
             var name=context.Message.Name;
             var id=context.Message.Id;
        }
}

在 Consume 方法中,您将收到“ProcessingQueue”类型的消息。您可以在此处访问属性..


推荐阅读