user9390243
user9390243

Reputation:

RabbitMQ Consumer not receiving messages sent from Api with .net core

I using .net core 2.1.0 and Masstransit and Rabbitmq.

My problem is when send message from controller , consumer cant receive the message

public static void ConfigureServices(IServiceCollection services, IConfiguration configuration)
    {
        var bus = Bus.Factory.CreateUsingRabbitMq(sbc =>
        {
            var host = sbc.Host(new Uri("rabbitmq://localhost/"), h =>
            {
                h.Username("guest");
                h.Password("guest");
            });
        });

        services.AddSingleton<IPublishEndpoint>(bus);
        services.AddSingleton<ISendEndpointProvider>(bus);
        services.AddSingleton<IBusControl>(bus);
        services.AddSingleton<IBus>(bus);

        bus.Start();
    }

Make Rabbitmq host.

[Route("api/[controller]")]
[ApiController]
public class BookController : ControllerBase
{
    private readonly IBus _bus;

    public BookController(IBus bus)
    {
        _bus = bus;
    }

    public void Post(CreateBookCommand createBookCommand)
    {
        _bus.Publish<CreateBookCommand>(createBookCommand);
    }
}

My controller.

public class BookCommandHandler : IConsumer<CreateBookCommand>
{
    private readonly IBookDomainService _bookService;
    public BookCommandHandler(IBookDomainService bookService)
    {
         _bookService = bookService;
    }

    public Task Consume(ConsumeContext<CreateBookCommand> context)
    {
         throw new NotImplementedException();
    }

    public void CreateBook(CreateBookCommand createBookCommand)
    {
         throw new NotImplementedException();
    }
}

My consumer.

Why comsumer cant receive message ?

Upvotes: 0

Views: 1232

Answers (1)

Alexey Zimarev
Alexey Zimarev

Reputation: 19630

You are not awaiting the asynchronous call when you publish, so nothing works.

You need to change your controller to be:

[Route("api/[controller]")]
[ApiController]
public class BookController : ControllerBase
{
    private readonly IBus _bus;

    public BookController(IBus bus)
    {
        _bus = bus;
    }

    public Task Post(CreateBookCommand createBookCommand)
        =>  _bus.Publish<CreateBookCommand>(createBookCommand);
}

This will work for a one-liner. If you will have more code there, you need to await explicitly:

public async Task Post(CreateBookCommand createBookCommand)
{
    // code

    await _bus.Publish<CreateBookCommand>(createBookCommand);
}

Notice, that commands are normally sent, not published.

I also hope that the service that hosts your consumers have the endpoint configured since you have not shared the startup code for that service.

Upvotes: 1

Related Questions