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
'Configure
方法更改为以下:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime applicationLifetime, IBusControl bus)
{
applicationLifetime.ApplicationStopping.Register(() => bus.Stop(TimeSpan.FromSeconds(10)));
....
处理正常关机。