2

I have read that when I use RabbitMQ the best practice is to use one connection per process, so I would like to create a singleton class for the rabbitmq connection. I would like to use the Lazy version of Singleton from: Implementing the Singleton Pattern in C#

I write this class:

public class RabbitConnection
{
    private static readonly Lazy<RabbitConnection>  Lazy = new Lazy<RabbitConnection>(() => new RabbitConnection());

    private RabbitConnection()
    {
        IConnectionFactory connectionFactory = new ConnectionFactory
        {
            HostName = "127.0.0.1",
            Port = 5672,
            UserName = "Username",
            Password = "********"
        };

        Connection = connectionFactory.CreateConnection();
    }

    public static RabbitConnection Instance
    {
        get { return Lazy.Value; }
    }

    public IConnection Connection { get; }
}

And use this like:

var channel = RabbitConnection.Instance.Connection.CreateModel();
channel.QueueDeclare("myQueue", true, false, false, null);
....

Is this implementation right or wrong? Thank you

pampua84
  • 696
  • 10
  • 33
  • `Lazy` (as used in your code, with the default `LazyThreadSafetyMode`) is safe to use **if you can be 100% sure the constructor will not throw an exception**. Since it can be hard to know that sometimes (without a thorough code analysis), I use `LazyWithNoExceptionCaching` instead - https://stackoverflow.com/a/42567351/34092 . – mjwills Feb 27 '19 at 09:06

1 Answers1

1

I have read that when I use RabbitMQ the best practice is to use one connection per process

No, this is not correct. You should use as many connections as your use-case demands and determine connection / channel count by using benchmarks of your expected workload.


NOTE: the RabbitMQ team monitors the rabbitmq-users mailing list and only sometimes answers questions on StackOverflow.

Luke Bakken
  • 8,993
  • 2
  • 20
  • 33
  • 1
    I wonder if the OP is referring to "The best practice is to reuse connections and multiplex a connection between threads with channels. You should ideally only have one connection per process, and then use a channel per thread in your application." from https://www.cloudamqp.com/blog/part1-rabbitmq-best-practice.html. – D. Cook Mar 29 '21 at 04:15