在ASP.NET Core应用程序中设置RabbitMQ使用者 [英] Setup RabbitMQ consumer in ASP.NET Core application

查看:690
本文介绍了在ASP.NET Core应用程序中设置RabbitMQ使用者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET Core应用程序,我想在其中使用RabbitMQ消息。

I have an ASP.NET Core application where I would like to consume RabbitMQ messages.

我已经在命令行应用程序中成功设置了发布者和使用者,但是我不确定如何在Web应用程序中正确设置它。

I have successfully set up the publishers and consumers in command line applications, but I'm not sure how to set it up properly in a web application.

我正在考虑在 Startup.cs ,但是当然它会在启动完成后就消失。

I was thinking of initializing it in Startup.cs, but of course it dies once startup is complete.

如何通过Web应用程序以正确的方式初始化使用者?

How to initialize the consumer in a the right way from a web app?

推荐答案

使用单例模式供消费者/听众在应用程序运行时保留它。使用 IApplicationLifetime 界面在应用程序启动/停止时启动/停止使用者。

Use the Singleton pattern for a consumer/listener to preserve it while the application is running. Use the IApplicationLifetime interface to start/stop the consumer on the application start/stop.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<RabbitListener>();
    }


    public void Configure(IApplicationBuilder app)
    {
        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()
    {
        _listener.Register();
    }

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




  • 您应该注意应用托管的位置。例如,IIS可以回收并停止运行代码。

  • 此模式可以扩展到一组侦听器。

  • 这篇关于在ASP.NET Core应用程序中设置RabbitMQ使用者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆