Configure RabbitMQ user in ASP.NET Core application

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

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

I thought to initialize it in Startup.cs , but of course it dies after the launch is complete.

How to properly initialize a user from a web application?

+18
source share
2 answers

Use the Singleton template for the consumer / listener to save it while the application is running. Use the IApplicationLifetime interface to start / stop the consumer when starting / stopping the application.

 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(); } } 
  • You must take care of where your application is located. For example, IIS may restart and stop code execution.
  • This template can be distributed to the listener pool.
+24
source

This is my listener:

 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(); } } 
+6
source

Source: https://habr.com/ru/post/1267130/


All Articles