RabbitMQ Connection Pool in C#

In C#, you can utilize the RabbitMQ.Client library to connect to and manipulate RabbitMQ message queues. Here is a simple example illustrating how to encapsulate a basic RabbitMQ connection pooling method.

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();
    }
}

Example usage:

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();

Please note that in actual usage, you may need to further refine and optimize the functionality of the connection pool according to your own needs, such as adding limits on connection pool size and connection reuse. The above example only provides a basic encapsulation framework, which you can adjust and expand according to your actual requirements.

bannerAds