You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在LINQPad 7中使用MassTransit 8请求时触发RequestTimeoutException

解决LINQPad中MassTransit 8请求/响应超时问题

你的问题核心是没有启动MassTransit总线,导致注册的消费者未被激活,消息发送后无人处理,最终触发超时。控制台应用通常会自动处理总线启动,但LINQPad脚本需要手动管理总线生命周期。

修正后的代码

async Task Main()
{
    IServiceCollection services = new ServiceCollection();
    services.AddMassTransit(x =>
    {
        x.AddConsumer<MyConsumer>(); // 泛型写法更简洁,替代typeof方式

        x.UsingRabbitMq((ctx, cfg) =>
        {
            cfg.Host("localhost", 5672, "/", h =>
            {
                h.Username("guest");
                h.Password("guest");
            });

            cfg.ConfigureEndpoints(ctx);
        });
    }); 
    
    var serviceProvider = services.BuildServiceProvider();
    
    // 获取总线控制对象并启动,激活消费者
    var busControl = serviceProvider.GetRequiredService<IBusControl>();
    await busControl.StartAsync(CancellationToken.None);
    
    try
    {
        var bus = serviceProvider.GetRequiredService<IBus>();
        var response = await bus.Request<MyRequest, MyResponse>(new MyRequest("Hi there"));
        response.Message.Dump("Response");
    }
    finally
    {
        // 脚本结束时停止总线,释放资源
        await busControl.StopAsync(CancellationToken.None);
    }
}

namespace MyNamespace
{
    public class MyRequest
    {
        public MyRequest() { }
        public MyRequest(string phrase) => Phrase = phrase;
        public string Phrase { get; set; }
    }

    public class MyResponse
    {
        public MyResponse() { }
        public MyResponse(string phrase) => Phrase = phrase;
        public string Phrase { get; set; }
    }

    public class MyConsumer : IConsumer<MyRequest>
    {
        public async Task Consume(ConsumeContext<MyRequest> context)
        {
            await context.RespondAsync(new MyResponse($"'{context.Message.Phrase}' to you too!"));
        }
    }
}

关键修改点

  • 启动总线:通过IBusControl.StartAsync()启动总线,这会激活所有注册的消费者,开始监听对应队列。
  • 区分IBus与IBusControl:IBus仅负责发送消息,IBusControl才是管理总线生命周期(启动/停止)的核心对象。
  • 添加finally块停止总线:避免LINQPad脚本结束后残留未释放的连接资源。
  • (可选)用泛型AddConsumer<MyConsumer>()替代typeof写法,代码更简洁。

原代码失效原因

你之前的代码仅构建了服务提供者,但MassTransit总线默认不会自动启动,消费者也不会被初始化。消息发送到RabbitMQ后,因无消费者监听请求队列,无人响应,最终触发RequestTimeoutException。

内容的提问来源于stack exchange,提问作者Mark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 06:36:38