Connecting to RabbitMQ Across Machines with .NET Client

My earlier article “Getting Started with RabbitMQ with .NET” showed how it’s easy to use the RabbitMQ .NET Client to connect to an instance of RabbitMQ running locally. In fact, omitting the code that declares a queue and consumes messages, we are essentially left with this:

        static void Main(string[] args)
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };

            using (var connection = factory.CreateConnection())
            {
                Console.WriteLine("Connected!");

                Console.ReadLine();
            }
        }

If we replace localhost with the hostname of a machine which actually does have a RabbitMQ instance running, however, we’re in for a surprise:

rabbitmq-connect-across-pcs-error

This StackOverflow answer suggests that we may need a username and password when setting up the connection. We can add these by changing our factory declaration as follows:

            var factory = new ConnectionFactory()
            {
                HostName = "MyOtherPc",
                UserName = "joe",
                Password = "joe"
            };

Connections using the default guest user don’t seem to work across machines, so we’re going to have to create a user account.

From the RabbitMQ Management UI, add a new user, giving him all tags available (administrator,monitoring,policymaker,management):

rabbitmq-new-user

That’s not enough to connect using our new user, though. You can see why if you click on the user:

rabbitmq-permission-virtual-directory

You can easily rectify the problem by clicking on that Set permission button to give the new user access to the root (/) virtual host. Note that this can also be done from the Virtual Hosts section… but doing it from the user page is easier.

rabbitmq-connect-across-machines-success

It works now. Yay.

Leave a Reply

Your email address will not be published. Required fields are marked *