1、exchange中的headers的使用
headers是采用muliple attributes代替routing key
x-match[all/any] all:所有的header头信息必须匹配
any:只要一个匹配即可
direct 只需要匹配一个routing key即可
而现在的headers匹配,必须满足部分或者全部的条件 【and/or】
if(name=='jack'&&name==20){
todo
}
if(name=='jack'||name==20){
todo
}
2、代码实现
1)生产者
//基础配置 ConnectionFactory factory = new ConnectionFactory() { HostName = "10.123.44.12", UserName = "datamip", Password = "datamip" }; //第一步:创建connection using (var connection = factory.CreateConnection()) { //第二步:创建channel using (var channel = connection.CreateModel()) { //第三步:创建exchange //channel.ExchangeDeclare("myfanoutexchange", ExchangeType.Fanout, true, false, null); var properties = channel.CreateBasicProperties(); properties.Headers = new Dictionary<string, object>(); properties.Headers.Add("username","jack"); //properties.Headers.Add("password", "12345"); //第四步:发布消息 for (int i = 0; i < 100; i++) { var msg = Encoding.UTF8.GetBytes(string.Format("{0}:{1}", i, "你好")); channel.BasicPublish("myheadersexchange1", string.Empty, basicProperties: properties, body: msg); } } } Console.WriteLine("生产成功!"); Console.ReadKey();
2)消费者
i)消费者1
//创建连接工厂 ConnectionFactory factory = new ConnectionFactory { UserName = "datamip",//用户名 Password = "datamip",//密码 HostName = "10.123.44.12"//rabbitmq ip }; //第一步:创建connection using (var connection = factory.CreateConnection()) { //第二步:创建channel using (var channel = connection.CreateModel()) { //第三步:生明交换机 channel.ExchangeDeclare("myheadersexchange1", ExchangeType.Headers, true, false, null); //第四步:声明队列,绑定交换机 channel.QueueDeclare("myheadersqueue1", true, false, false, null); channel.QueueBind("myheadersqueue1", "myheadersexchange1", 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.ToArray()); Console.WriteLine(msg); }; //消费 channel.BasicConsume("myheadersqueue1", true, consumer); Console.ReadKey(); } }
ii)消费者2
//创建连接工厂 ConnectionFactory factory = new ConnectionFactory { UserName = "datamip",//用户名 Password = "datamip",//密码 HostName = "10.123.44.12"//rabbitmq ip }; //第一步:创建connection using (var connection = factory.CreateConnection()) { //第二步:创建channel using (var channel = connection.CreateModel()) { //第三步:生明交换机 channel.ExchangeDeclare("myheadersexchange1", ExchangeType.Headers, true, false, null); //第四步:声明队列,绑定交换机 channel.QueueDeclare("myheadersqueue2", true, false, false, null); channel.QueueBind("myheadersqueue2", "myheadersexchange1", string.Empty, new Dictionary<string, object>() { {"x-match","any" }, {"username","jack" }, {"password","12345" } }); //处理消息 EventingBasicConsumer consumer = new EventingBasicConsumer(channel); consumer.Received += (sender, e) => { var msg = Encoding.UTF8.GetString(e.Body.ToArray()); Console.WriteLine(msg); }; //消费 channel.BasicConsume("myheadersqueue2", true, consumer); Console.ReadKey(); } }
iii)效果
3、图形解释