在ASP.NET Core应用程序中设置RabbitMQ使用者

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

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

我想在Startup.cs中初始化它,但当然一旦启动完成它就会死掉。

如何从Web应用程序以正确的方式初始化消费者?

使用Singleton模式为使用者/监听器在应用程序运行时保留它。 使用IApplicationLifetime接口在应用程序启动/停止时启动/停止使用者。

 public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddSingleton(); } 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(); var lifetime = app.ApplicationServices.GetService(); 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可以回收并阻止您的代码运行。
  • 此模式可以扩展到一个侦听器池。

这是我的听众:

 public class RabbitListener { ConnectionFactory factory { get; set; } IConnection connection { get; set; } IModel channel { get; set; } public void Register() { channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); int m = 0; }; channel.BasicConsume(queue: "hello", autoAck: true, consumer: consumer); } public void Deregister() { this.connection.Close(); } public RabbitListener() { this.factory = new ConnectionFactory() { HostName = "localhost" }; this.connection = factory.CreateConnection(); this.channel = connection.CreateModel(); } }