RabbitMQ通过Exchange.headers属性代替routekey,x-match实现队列精准匹配
消费者:
static void Main(string[] args) { ConnectionFactory factory = new ConnectionFactory() { HostName = "192.168.254.40", UserName = "admin", Password = "admin", }; //第一步:创建connection var connection = factory.CreateConnection(); //第二步:创建一个channel var channel = connection.CreateModel(); //第三步:申明交换机【因为rabbitmq已经有了自定义的ampq default exchange】 channel.ExchangeDeclare("myheadersexchange", ExchangeType.Headers, true, false, null); //第四步:创建一个队列(queue) channel.QueueDeclare("myheadersqueue", true, false, false, null); //将queue绑定到exchange之上。。。。 channel.QueueBind("myheadersqueue", "myheadersexchange", string.Empty, new Dictionary<string, object>() { {"x-match", "all"}, {"username", "jack"}, {"password", "12345" } }); EventingBasicConsumer consumer = new EventingBasicConsumer(channel); consumer.Received += (sender, e) => { var msg = Encoding.UTF8.GetString(e.Body); Console.WriteLine(msg); }; channel.BasicConsume("myheadersqueue", true, consumer); Console.WriteLine("consumer1 端启动完毕!!!"); Console.Read(); }
生产者:
static void Main(string[] args) { ConnectionFactory factory = new ConnectionFactory() { HostName = "192.168.254.40", UserName = "admin", Password = "admin", }; //第一步:创建connection var connection = factory.CreateConnection(); //第二步:创建一个channel var channel = connection.CreateModel(); var properties = channel.CreateBasicProperties(); properties.Headers = new Dictionary<string, object>(); properties.Headers.Add("password", "12345"); properties.Headers.Add("username", "jack"); for (int i = 0; i < 100; i++) { var msg = Encoding.UTF8.GetBytes(string.Format("{0} :{1}", i, "你好")); //第五步:发布消息 channel.BasicPublish("myheadersexchange", routingKey: string.Empty, basicProperties: properties, body: msg); Console.WriteLine(i); } }
headers 是采用多个属性代替routing key
x-match [all/any] all: 所有的header头信息必须匹配。。。
any: 只要有一个匹配就ok了。。。。
direct exchange: 只需要匹配一个routingkey就可以了。。。。
而现在的headers匹配,必须是满足一个或者全部的条件。。。 【and /or】的关系。。。
if(name=="jack" || age==20){
queue1.add(msg);
}
if(name=="jack" && age==20){
queue2.add(msg);
}
在webui上看一下:
x-match: any
x-match:all
key,value的顺序没有特别大的关系,因为headers.erl中会将这些key按照字母进行排序。。。