尝试使用MassTransit.RabbitMQ
版本4.0.1.1378-develop
,ASP.NET Core 2 Web应用程序和.NET Core 2控制台项目实现请求/响应方案。
以下是在我的ASP.NET Core 2.0应用程序中创建总线和请求客户端的代码:
var bus = Bus.Factory.CreateUsingRabbitMq(sbc =>
sbc.Host(new Uri("rabbitmq://localhost"), h =>
{
h.Username("guest");
h.Password("guest");
})
);
services.AddSingleton<IPublishEndpoint>(bus);
services.AddSingleton<IBusControl>(bus);
var requestTimeout = TimeSpan.FromSeconds(10);
var address = new Uri("rabbitmq://localhost/myqueue");
services.AddScoped<IRequestClient<SubmitOrder, OrderSubmitResult>>(ctx => new MessageRequestClient<SubmitOrder, OrderSubmitResult>(bus, address, requestTimeout));
然后使用已注入我的控制器的IRequestClient<SubmitOrder, OrderSubmitResult>
,我发送请求如下:
private readonly IRequestClient<SubmitOrder, OrderSubmitResult> _client;
public async Task<ActionResult> SendRequest(string id)
{
var result = await _client.Request(new SubmitOrder());
...
}
最后,我尝试向客户发送响应的方式:
var bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
{
var host = cfg.Host(new Uri("rabbitmq://localhost"), h =>
{
h.Username("guest");
h.Password("guest");
});
cfg.ReceiveEndpoint(host, "myqueue", ep =>
{
ep.Handler<SubmitOrder>(context => context.RespondAsync(new OrderSubmitResult()));
// async version
//ep.Handler<SubmitOrder>(async context =>
//{
// await context.RespondAsync(new OrderSubmitResult());
//});
// with a Consumer
//ep.Consumer<SubmitOrderConsumer>();
// with a single Consumer
//ep.Instance(new SubmitOrderConsumer());
});
});
bus.Start();
我在公交车上收到请求,并发送适当的回复。但我总是在客户端获得RequestTimeoutException
,并且上述方法都不起作用。
更新
代码没问题。我忘了在客户端启动总线(bus.start
):/
@Chris:感谢您在短时间内添加完整的工作样本。我建议添加services.AddSingleton<IBusControl>(bus);
,然后将Startup.cs
的{{1}}方法更改为以下内容:
Configure
处理正常关机。
答案 0 :(得分:3)
我已经构建了一个示例来说明如何正确执行此操作,包括使用ASP.NET Core 2,Web应用程序和控制台应用程序。
https://github.com/MassTransit/Sample-DotNetCore-Request
享受!