Search code examples
c#design-patternsrabbitmq

Creating a class for RabbitMQ Client Connection


I want to create a class, kind of like a wrapper for a RabbitMQ connection, to publish messages to an exchange. This will be a class library used by another system.

My question is pretty straightforward: How do I go about closing and opening the connection?

My initial idea is something like this:

public class RabbitConnection
{
    private readonly IConnection conn;

    public RabbitConnection() {
        try {
         var factory = new ConnectionFactory() {...}
         this.conn = factory.CreateConnection();
        }
        catch {
         ...
        }
    }

    ...

    public void Publish<T>(T @event) where T : class {
        using (var channel = conn.CreateModel()) {
            ...
            channel.BasicPublish(...);
        }
    }
}

Is this the best way if it isn't what do I search to find the best pattern?

Thanks is advance!


Solution

  • Open your connection and channel in the constructor, and close them when the instance is disposed. It is very important that RabbitConnection is long-lived. If you create and close connections over and over (worst-case is per-message), it will drastically reduce performance as well as increase load on your RabbitMQ server and client application machine.