为什么MassTransit只在一个线程上消费消息

时间:2016-10-07 14:49:04

标签: rabbitmq masstransit

我在常规控制台应用程序中有以下简单代码,并且希望(某些)命令并行使用。我认为UseConcurrencyLimit会设置并发线程的数量。我所看到的是,RabbitMQ确实有10条未经处理的消息,但消费者会连续消耗它们,每个console.writeline之间暂停一秒钟。我必须遗漏一些明显的东西,但我不明白。

public static class EventHandler
{
    public static void Run()
    {
        var personQueueName = "RabbitMqPoc.Person";

        var busControl = Bus.Factory.CreateUsingRabbitMq(cfg =>
        {

            cfg.UseConcurrencyLimit(10);

            var host = cfg.Host(new Uri("rabbitmq://localhost"), h =>
            {
                h.Username("guest");
                h.Password("guest");
            });

            cfg.ReceiveEndpoint(host, personQueueName, e =>
            {
                e.UseConcurrencyLimit(10);
                e.PrefetchCount = 10;
                e.Consumer<PersonConsumer>();
            });
        });

        var personSendEndpoint = busControl.GetSendEndpoint(new Uri($"rabbitmq://localhost/{personQueueName}")).Result;

        busControl.Start();

        foreach (var x in Enumerable.Range(1, 20))
        {
            personSendEndpoint.Send(new PersonUpdated() { Name = "Mina Ives", Key = Guid.NewGuid() });
        }

        Console.ReadLine();
        busControl.Stop();
    }
}

internal class PersonConsumer : IConsumer<IPersonUpdated>
{
    public async Task Consume(ConsumeContext<IPersonUpdated> context)
    {
        Thread.Sleep(1000);
        Console.WriteLine($"Updated {context.Message.Name}");
    }

}

1 个答案:

答案 0 :(得分:1)

Thread.Sleep(1000);更改为await Task.Delay(1000);可以解决您所看到的问题。

Thread.Sleep出于某种原因对TPL造成了严重破坏。