This is the eighth and final installment to the series: RabbitMQ for Windows. In thelast installment, we walked through creating a topic exchange example. As the last installment, we’ll walk through a headers exchange example.
Headers exchanges examine the message headers to determine which queues a message should be routed to. As discussed earlier in this series, headers exchanges are similar to topic exchanges in that they allow you to specify multiple criteria, but offer a bit more flexibility in that the headers can be constructed using a wider range of data types (1).
To subscribe to receive messages from a headers exchange, a dictionary of headers is specified as part of the binding arguments. In addition to the headers, a key of “x-match” is also included in the dictionary with a value of “all”, specifying that messages must be published with all the specified headers in order to match, or “any”, specifying that the message needs to only have one of the specified headers specified.
As our final example, we’ll create a Producer application which publishes the message “Hello, World!” using a headers exchange. Here’s our Producer code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
using RabbitMQ.Client;
using RabbitMQ.Client.Framing.v0_9_1;
namespace Producer
{
class Program
{
const string ExchangeName = "header-exchange-example";
static void Main(string[] args)
{
var connectionFactory = new ConnectionFactory();
connectionFactory.HostName = "localhost";
IConnection connection = connectionFactory.CreateConnection();
IModel channel = connection.CreateModel();
channel.ExchangeDeclare(ExchangeName, ExchangeType.Headers, false, true, null);
byte[] message = Encoding.UTF8.GetBytes("Hello, World!");
var properties = new BasicProperties();
properties.Headers = new Dictionary<string, object>();
properties.Headers.Add("key1", "12345");
TimeSpan time = TimeSpan.FromSeconds(10);
var stopwatch = new Stopwatch();
Console.WriteLine("Running for {0} seconds", time.ToString("ss"));
stopwatch.Start();
var messageCount = 0;
while (stopwatch.Elapsed < time)
{
channel