在C#中,可以通過使用RabbitMQ.Client庫來連接和操作RabbitMQ消息隊列。以下是一個簡單的示例,展示了如何封裝一個基本的RabbitMQ連接池方法:
using System;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
public class RabbitMQPool
{
private readonly string _connectionString;
private IConnection _connection;
private IModel _channel;
public RabbitMQPool(string connectionString)
{
_connectionString = connectionString;
CreateConnection();
}
public void CreateConnection()
{
var factory = new ConnectionFactory
{
Uri = new Uri(_connectionString)
};
_connection = factory.CreateConnection();
_channel = _connection.CreateModel();
}
public void Publish(string exchange, string routingKey, byte[] message)
{
_channel.BasicPublish(exchange, routingKey, null, message);
}
public void Consume(string queue, Action<byte[]> callback)
{
var consumer = new EventingBasicConsumer(_channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
callback(body);
};
_channel.BasicConsume(queue, true, consumer);
}
public void CloseConnection()
{
_channel?.Close();
_connection?.Close();
}
}
使用示例:
var connectionString = "amqp://guest:guest@localhost:5672";
var pool = new RabbitMQPool(connectionString);
// 發布消息
var exchange = "myExchange";
var routingKey = "myRoutingKey";
var message = Encoding.UTF8.GetBytes("Hello RabbitMQ");
pool.Publish(exchange, routingKey, message);
// 消費消息
var queue = "myQueue";
pool.Consume(queue, (body) =>
{
var receivedMessage = Encoding.UTF8.GetString(body);
Console.WriteLine(receivedMessage);
});
// 關閉連接
pool.CloseConnection();
注意:在實際使用中,你可能需要根據自己的需求進一步完善和優化連接池的功能,例如添加連接池大小限制、連接復用等。上述示例僅提供了一個基本的封裝框架,你可以根據自己的實際需求進行調整和擴展。