1、exchange [fanout] 多播
应用场景
1)订单流程:提交订单后,同时发送短信和邮件
2)cs软件弹出消息
普通情况下,使用轮询方式,在cs中绑定fanout exchange,如果存在消息,及时推送
3)客户关怀和千人千面
taobao=> 催付,付款后提醒、发货提醒、签收提醒
=> 给用户关联推荐 彩信、短信、邮件等发送关联推荐
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); //第四步:发布消息,直接绑定对应的routingkey for (int i = 0; i < 100; i++) { var msg = Encoding.UTF8.GetBytes(string.Format("{0}:{1}", i, "你好")); channel.BasicPublish("myfanoutexchange",string.Empty, basicProperties: null, body: msg); } } } Console.WriteLine("生产成功!"); Console.ReadKey();
2)消费者
消费者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("myfanoutexchange", ExchangeType.Direct, true, false, null); //第四步:声明队列,绑定交换机 channel.QueueDeclare("myfanoutqueue1", true, false, false, null); channel.QueueBind("myfanoutqueue1", "myfanoutexchange", string.Empty, null); //处理消息 EventingBasicConsumer consumer = new EventingBasicConsumer(channel); consumer.Received += (sender, e) => { var msg = Encoding.UTF8.GetString(e.Body.ToArray()); Console.WriteLine(msg); }; //消费 channel.BasicConsume("myfanoutqueue1", true, consumer); Console.ReadKey(); } }
消费者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("myfanoutexchange", ExchangeType.Direct, true, false, null); //第四步:声明队列,绑定交换机 channel.QueueDeclare("myfanoutqueue2",true,false,false,null); channel.QueueBind("myfanoutqueue2", "myfanoutexchange", string.Empty, null); //处理消息 EventingBasicConsumer consumer = new EventingBasicConsumer(channel); consumer.Received += (sender,e)=> { var msg = Encoding.UTF8.GetString(e.Body.ToArray()); Console.WriteLine(msg); }; //消费 channel.BasicConsume("myfanoutqueue2", true, consumer); Console.ReadKey(); } }
3)效果
3、图形解释