我有一个服务需要在启动时连接到另一个服务。
另一个服务是 Rabbitmq
代理。
我正在监听来自 Rabbitmq
的某些事件,所以我需要从应用程序开始时就激活它。
我需要连接到两个不同的 VHost
,因此需要创建两个连接。
问题是当我启动应用程序时,它会不断地创建连接,直到服务器崩溃!
在 Rabbitmq 管理中,可以看到创建了大量的 Connection
和 Channels
。
我找不到原因。
通常,我想知道在 .NET Core 应用程序启动时连接到其他服务的正确方法是什么。
我使用以下代码来实现:
public void ConfigureServices(IServiceCollection services)
{
.....
services.AddSingleton<RabbitConnectionService>();
...
ActivatorUtilities.CreateInstance<RabbitConnectionService>(services.BuildServiceProvider());
}
在
RabbitConnectionService
的构造函数中,我正在连接RabbitMQ
。public RabbitConnectionService(IConfiguration configuration)
{
ServersMessageQueue = new MessageQueue(configuration.GetConnectionString("FirstVhost"), "First");
ClientsMessageQueue = new MessageQueue(configuration.GetConnectionString("SecondVhost"), "Second");
}
消息队列类:
public class MessageQueue
{
private IConnection connection;
private string RabbitURI;
private string ConnectionName;
static Logger _logger = LogManager.GetCurrentClassLogger();
public MessageQueue(string connectionUri, string connectionName)
{
ConnectionName = connectionName;
RabbitURI = connectionUri;
connection = CreateConnection();
}
private IConnection CreateConnection()
{
ConnectionFactory factory = new ConnectionFactory();
factory.Uri = new Uri(RabbitURI);
factory.AutomaticRecoveryEnabled = true;
factory.RequestedHeartbeat = 10;
return factory.CreateConnection(ConnectionName);
}
public IModel CreateChannel()
{
return connection.CreateModel();
}
...
}
ActivatorUtilities.CreateInstance
,然后不对结果进行任何操作? - Ian KempConfigureServices
方法的命名不够合适,它应该被称为ConfigureDependencies
或类似的名称。无论如何,你正在寻找的是后台任务,MSDN有相关文档:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2&tabs=visual-studio#consuming-a-scoped-service-in-a-background-task-1 - Ian Kemp