消費者1:spa
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:code
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(); }
生產者:orm
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,兩個消費端綁定不一樣的隊列都獲得了相同的消息blog