使用.net 6 封装一个RabbitMQ 帮助类
时间: 2024-03-01 08:28:32 浏览: 190
好的,下面是一个简单的 RabbitMQ 帮助类的封装示例,使用 .NET 6:
```csharp
using System;
using System.Text;
using RabbitMQ.Client;
namespace RabbitMQHelper
{
public class RabbitMQHelper
{
private readonly string _hostName;
private readonly int _port;
private readonly string _userName;
private readonly string _password;
private readonly string _queueName;
private readonly string _exchangeName;
private readonly string _routingKey;
private IConnection _connection;
private IModel _channel;
public RabbitMQHelper(string hostName, int port, string userName, string password, string queueName, string exchangeName, string routingKey)
{
_hostName = hostName;
_port = port;
_userName = userName;
_password = password;
_queueName = queueName;
_exchangeName = exchangeName;
_routingKey = routingKey;
CreateConnection();
}
private void CreateConnection()
{
var factory = new ConnectionFactory
{
HostName = _hostName,
Port = _port,
UserName = _userName,
Password = _password
};
_connection = factory.CreateConnection();
_channel = _connection.CreateModel();
_channel.ExchangeDeclare(_exchangeName, ExchangeType.Direct, durable: true);
_channel.QueueDeclare(_queueName, durable: true, exclusive: false, autoDelete: false);
_channel.QueueBind(_queueName, _exchangeName, _routingKey);
}
public void PublishMessage(string message)
{
var body = Encoding.UTF8.GetBytes(message);
var properties = _channel.CreateBasicProperties();
properties.Persistent = true;
_channel.BasicPublish(_exchangeName, _routingKey, properties, body);
}
public string ConsumeMessage()
{
var message = string.Empty;
var consumer = new EventingBasicConsumer(_channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
message = Encoding.UTF8.GetString(body);
};
_channel.BasicConsume(_queueName, true, consumer);
return message;
}
public void CloseConnection()
{
_channel.Close();
_connection.Close();
}
}
}
```
这个类有一个构造函数,需要传入 RabbitMQ 服务器的主机名、端口、用户名、密码、队列名、交换机名和路由键。然后,它会创建一个连接和一个通道,并使用这些参数声明交换机和队列,并将它们绑定在一起。`PublishMessage`方法可以用于发布消息,`ConsumeMessage`方法可以用于消费消息。最后,可以使用`CloseConnection`方法关闭连接。
使用示例:
```csharp
using RabbitMQHelper;
var rabbitMQHelper = new RabbitMQHelper("localhost", 5672, "guest", "guest", "my_queue", "my_exchange", "my_routing_key");
rabbitMQHelper.PublishMessage("Hello, RabbitMQ!");
var message = rabbitMQHelper.ConsumeMessage();
Console.WriteLine(message);
rabbitMQHelper.CloseConnection();
```
这是一个简单的示例,你可以根据自己的需求进行修改和扩展。
阅读全文