public static void SendMessage() { var factory = new ConnectionFactory(); factory.HostName = "192.168.1.117"; factory.UserName = "witbank"; factory.Password = "123456"; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { const string EXCHANGE_NAME = "logs"; const string ROUTING_KEY = ""; channel.ExchangeDeclare(EXCHANGE_NAME, "fanout");//广播 while (true) { string message = "请输入要发送的信息"; Console.WriteLine(message); message = Console.ReadLine(); var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(EXCHANGE_NAME, ROUTING_KEY, null, body);//不需要指定routing key,设置了fanout,指了也没有用. Console.WriteLine(" [x] Sent {0}", message); } } } }
public static void ReceiveMessage() { var factory = new ConnectionFactory(); factory.HostName = "192.168.1.117"; factory.UserName = "witbank"; factory.Password = "123456"; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { const string EXCHANGE_NAME = "logs"; const string ROUTING_KEY = ""; channel.ExchangeDeclare(EXCHANGE_NAME, "fanout");//广播 QueueDeclareOk queueOk = channel.QueueDeclare();//每当Consumer连接时,我们需要一个新的,空的queue。因为我们不对老的log感兴趣。幸运的是,如果在声明queue时不指定名字,那么RabbitMQ会随机为我们选择这个名字。 ////现在我们已经创建了fanout类型的exchange和没有名字的queue(实际上是RabbitMQ帮我们取了名字)。 ////那exchange怎么样知道它的Message发送到哪个queue呢?答案就是通过bindings:绑定。 string queueName = queueOk.QueueName;//得到RabbitMQ帮我们取了名字 channel.QueueBind(queueName, EXCHANGE_NAME, ROUTING_KEY);//不需要指定routing key,设置了fanout,指了也没有用. var consumer = new QueueingBasicConsumer(channel); channel.BasicConsume(queueName, true, consumer); Console.WriteLine(" [*] Waiting for messages." + "To exit press CTRL+C"); while (true) { var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();//挂起的操作 var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); } } } }