1

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)));
....

处理正常关机。

4

1 回答 1

3

我构建了一个示例来展示如何正确执行此操作,包括使用 ASP.NET Core 2、Web 应用程序和控制台应用程序。

https://github.com/MassTransit/Sample-DotNetCore-Request

享受!

于 2018-01-09T20:14:12.207 回答