ASP.NET Core应用程序中的RabbitMQ使用者发布了Web请求

时间:2019-05-08 08:50:48

标签: c# asp.net-core .net-core rabbitmq

总结我如何解决Setup RabbitMQ consumer in ASP.NET Core application 但是如果我进行Web请求,则我的Rabbit消费者在线,如果我启动IIS而不启动浏览器请求,则不会启动Rabbit消费者。 有谁知道为什么吗? Web应用程序可以完成Web应用程序和Windows服务的工作,还是一个坏主意。

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSingleton<RabbitListener>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseRabbitListener();
        ...
    }

}
public static class ApplicationBuilderExtentions
{
    //the simplest way to store a single long-living object, just for example.
    private static RabbitListener _listener { get; set; }

    public static IApplicationBuilder UseRabbitListener(this IApplicationBuilder app)
    {
        _listener = app.ApplicationServices.GetService<RabbitListener>();


        var lifetime = app.ApplicationServices.GetService<IApplicationLifetime>();

        lifetime.ApplicationStarted.Register(OnStarted);

        //press Ctrl+C to reproduce if your app runs in Kestrel as a console app
        lifetime.ApplicationStopping.Register(OnStopping);

        return app;
    }

    private static void OnStarted()
    {
        foreach (var o in LogOptions.Options)
            _listener.NewRouteAdd(o.QueueString);
        _listener.Register();
    }

    private static void OnStopping()
    {
        _listener.Deregister();
    }
}

1 个答案:

答案 0 :(得分:0)

当您的应用程序收到第一个HTTP请求时,OnStart()运行一次 我认为对您来说最好的选择是创建一个Windows服务来使用消息或任何保持活动连接的应用程序

我为您建议以下链接: https://www.cloudamqp.com/blog/2018-01-19-part4-rabbitmq-13-common-errors.html https://www.cloudamqp.com/blog/2017-12-29-part1-rabbitmq-best-practice.html