我使用.net core 2.1.0以及Masstransit和Rabbitmq。
我的问题是从控制器发送消息时,消费者无法接收到消息
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();
}
设置Rabbitmq主机。
[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);
}
}
我的控制器。
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();
}
}
我的消费者。
为什么消费者不能接收消息?
答案 0 :(得分:1)
发布时您没有等待异步调用,所以没有任何作用。
您需要将控制器更改为:
[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);
}
这将适用于单线。如果您在那里需要更多代码,则需要明确等待:
public async Task Post(CreateBookCommand createBookCommand)
{
// code
await _bus.Publish<CreateBookCommand>(createBookCommand);
}
注意,命令通常是发送而不是发布。
我还希望托管您的使用者的服务具有endpoint configured,因为您尚未共享该服务的启动代码。