消費者: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("mytopicexchange", ExchangeType.Topic, true, false, null); //第四步:建立一個隊列(queue) channel.QueueDeclare("mytopicqueue", true, false, false, null); //將queue綁定到exchange之上。。。。 channel.QueueBind("mytopicqueue", "mytopicexchange", "*.com", null); EventingBasicConsumer consumer = new EventingBasicConsumer(channel); consumer.Received += (sender, e) => { var msg = Encoding.UTF8.GetString(e.Body); Console.WriteLine(msg); }; channel.BasicConsume("mytopicqueue", true, consumer); Console.WriteLine("consumer1 端啓動完畢!!!"); Console.Read(); }
生產者: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(); for (int i = 0; i < 100; i++) { var msg = Encoding.UTF8.GetBytes(string.Format("{0} :{1}", i, "你好")); var routingKey = i % 13 == 0 ? "a.com" : "*.cn"; //第五步:發佈消息 channel.BasicPublish("mytopicexchange", routingKey: routingKey, basicProperties: null, body: msg); Console.WriteLine(i); } }
當生產者routingkey 爲a.com,消費者*.com 會匹配上orm