Setup RabbitMQ consumer in ASP.NET Core application(在 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.
如何从网络应用以正确的方式初始化消费者?
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 消费者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 ASP.NET Core 应用程序中设置 RabbitMQ 消费者
基础教程推荐
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
