您可以将RabbitMQ消费者代码封装在一个实现了 IHostedService
接口的服务类中,并通过 AddHostedService
方法将其添加到 ASP.NET Core 应用程序中,使其在应用程序启动时自动启动并持续运行。
以下是一个实现了 IHostedService
接口的 RabbitMQ 消费者服务的示例代码:
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
public class ConsumerService : IHostedService
{
private readonly IConnection _connection;
private readonly IModel _channel;
public ConsumerService()
{
var factory = new ConnectionFactory()
{
HostName = "rabbitmq.example.com",
Port = 5672,
UserName = "guest",
Password = "guest",
VirtualHost = "/"
};
_connection = factory.CreateConnection();
_channel = _connection.CreateModel();
_channel.ExchangeDeclare(exchange: "topic_logs",
type: ExchangeType.Topic);
var queueName = _channel.QueueDeclare().QueueName;
_channel.QueueBind(queue: queueName,
exchange: "topic_logs",
routingKey: "anonymous.info");
var consumer = new EventingBasicConsumer(_channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received '{0}':'{1}'", ea.RoutingKey, message);
};
_channel.BasicConsume(queue: queueName,
autoAck: true,
consumer: consumer);
}
public Task StartAsync(CancellationToken cancellationToken)
{
Console.WriteLine("ConsumerService started.");
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_channel.Close(200, "Goodbye.");
_connection.Close();
Console.WriteLine("ConsumerService stopped.");
return Task.CompletedTask;
}
}
在上述示例代码中,ConsumerService
类实现了 IHostedService
接口并使用了 RabbitMQ 的消费者代码实现了一个后台任务。在 StartAsync
方法中,我们输出了一段信息以表示服务启动。在 StopAsync
方法中,我们关闭了 RabbitMQ 的通道和连接并输出了一段消息以表示服务停止。
将该示例代码添加到您的应用程序中,可以这样注册并启动它:
services.AddHostedService<ConsumerService>();
这样,当您启动您的应用程序时,您的 RabbitMQ 消费者服务将自动启动并持续运行,直到您停止应用程序。