消费者1:
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("myfanoutexchange", ExchangeType.Fanout, true, false, null); //第四步:创建一个队列(queue) channel.QueueDeclare("myfanoutqueue", true, false, false, null); //将queue绑定到exchange之上。。。。 channel.QueueBind("myfanoutqueue", "myfanoutexchange", string.Empty, null); EventingBasicConsumer consumer = new EventingBasicConsumer(channel); consumer.Received += (sender, e) => { var msg = Encoding.UTF8.GetString(e.Body); Console.WriteLine(msg); }; channel.BasicConsume("myfanoutqueue", true, consumer); Console.WriteLine("consumer1 端启动完毕!!!"); Console.Read(); }
消费者2:
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("myfanoutexchange", ExchangeType.Fanout, true, false, null); //第四步:创建一个队列(queue) channel.QueueDeclare("myfanoutqueue2", true, false, false, null); //将queue绑定到exchange之上。。。。 channel.QueueBind("myfanoutqueue2", "myfanoutexchange", string.Empty, null); EventingBasicConsumer consumer = new EventingBasicConsumer(channel); consumer.Received += (sender, e) => { var msg = Encoding.UTF8.GetString(e.Body); Console.WriteLine(msg); }; channel.BasicConsume("myfanoutqueue2", true, consumer); Console.WriteLine("consumer2 端启动完毕!!!"); 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(); for (int i = 0; i < 10; i++) { var msg = Encoding.UTF8.GetBytes(string.Format("{0} :{1}", i, "你好")); //第五步:发布消息 channel.BasicPublish("myfanoutexchange", routingKey: string.Empty, basicProperties: null, body: msg); Console.WriteLine(i); } }
先启动消费端进行绑定,生产者发送消息到exchange,两个消费端绑定不同的队列都得到了相同的消息