Today I want to talk about a specific feature in RabbitMQ and how we can use this feature with my favorite messaging library MassTransit.
Virtual Hosts
With virtual hosts you can create a logical grouping in your RabbitMQ cluster. Every exchange, queue, binding, user permissions, and so on is bound to a specific virtual host and isolated from the other virtual hosts. This helps to avoid naming collisions.
There is always at least one virtual host in use; the default one is ‘/’.
To create a new virtual host in your RabbitMQ cluster, you can use the rabbitmqctl's add_vhost command:
rabbitmqctl add_vhost development
Or you can use the RabbitMQ Management portal:
- In the Management Portal go to the Admin tab and click on the Virtual Hosts section on the right:
- Go to the Add Virtual Host form and enter a name and an optional description and tags:
- Click on Add virtual host to create the new virtual host.
Remark: Be aware that virtual hosts are a security boundary, so I would recommend to create different users per virtual host.
Using Virtual Hosts in MassTransit
Now that we have a new Virtual Host created, let’s see how we can use this in MassTransit.
Let’s have a look at a simple example from the MassTransit documentation:
namespace RabbitMqConsoleListener; | |
using System.Threading.Tasks; | |
using MassTransit; | |
using Microsoft.Extensions.Hosting; | |
public static class Program | |
{ | |
public static async Task Main(string[] args) | |
{ | |
await Host.CreateDefaultBuilder(args) | |
.ConfigureServices(services => | |
{ | |
services.AddMassTransit(x => | |
{ | |
x.UsingRabbitMq((context, cfg) => | |
{ | |
// The "/" refers to 👇 the virtual host | |
cfg.Host("localhost", "/", h => | |
{ | |
h.Username("guest"); | |
h.Password("guest"); | |
}); | |
}); | |
}); | |
}) | |
.Build() | |
.RunAsync(); | |
} | |
} |
In the example above, the virtual host is passed as a second parameter after the servername in the Host()
method:
You can also specify it through the URI:
public static class Program | |
{ | |
public static async Task Main(string[] args) | |
{ | |
// The 'development' part in the URI refers 👇 to the vhost | |
var uri=new Uri("rabbitmq://localhost:5672/development"); | |
await Host.CreateDefaultBuilder(args) | |
.ConfigureServices(services => | |
{ | |
services.AddMassTransit(x => | |
{ | |
x.UsingRabbitMq((context, cfg) => | |
{ | |
cfg.Host(uri, h => | |
{ | |
h.Username("guest"); | |
h.Password("guest"); | |
}); | |
}); | |
}); | |
}) | |
.Build() | |
.RunAsync(); | |
} | |
} |