Exchanges概念
RabbitMQ消息传递模型的核心思想是:生产者生产的消息从不会直接发送到队列。实际上,通常生产者甚至都不知道这些消息传递到了哪些队列中。
相反,生产者只能将消息发送到交换机,交换机工作的内容很简单,一方面它接收来自生产者的消息,另一方面将它们推入队列。交换机必须明确知道如何处理收到的消息。是应该把这些消息放到特定队列还是说把他们放到许多队列中还是说应该丢失它们。这就由交换机的类型来决定。
Exchanges的类型
直接(direct),主题(topic),标题(headers),扇出(fanout)
扇出(fanout)
它是将接收到的所有消息广播到它知道的所有队列中。系统中默认有些exchange类型
生者者代码:
package com.atguigu.rabbitmq.five;
import com.atguigu.rabbitmq.utils.RabbitMqUtils;
import com.rabbitmq.client.Channel;
import java.util.Scanner;
public class EmitLog {
private static final String EXCHANGE_NAME="logs";
public static void main(String[] args) throws Exception {
try (Channel channel = RabbitMqUtils.getChannel()){
/**
* 声明一个exchange
* 1、exchange的名称
* 2、exchange的类型
*/
channel.exchangeDeclare(EXCHANGE_NAME,"fanout");
Scanner sc = new Scanner(System.in);
System.out.println("请输入信息");
while (sc.hasNext()){
String message = sc.nextLine();
channel.basicPublish(EXCHANGE_NAME,"",null,message.getBytes("UTF-8"));
System.out.println("生产者发出消息:" + message);
}
}
}
}
消费者1代码
package com.atguigu.rabbitmq.five;
import com.atguigu.rabbitmq.utils.RabbitMqUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;
public class ReceiveLogs01 {
private static final String EXCHANGE_NAME = "logs";
public static void main(String[] args) throws Exception {
Channel channel = RabbitMqUtils.getChannel();
channel.exchangeDeclare(EXCHANGE_NAME,"fanout");
/**
* 生产一个临时的队列,队列的名称是随机的
* 当消费者断开和该队列的连接时i,队列自动删除
*/
String queueName = channel.queueDeclare().getQueue();
//把该临时队列绑定我们的exchage 其中routingkey(也称之为bingding key)为空字符串
channel.queueBind(queueName,EXCHANGE_NAME,"");
System.out.println("等待接收消息,把接收到的消息打印在屏幕........");
DeliverCallback deliverCallback =(consumerTag,deliver)->{
String message = new String(deliver.getBody(), "UTF-8");
System.out.println("控制台打印接收到的消息" + message);
};
channel.basicConsume(queueName,true,deliverCallback,consumerTag->{});
}
}
消费者2代码
package com.atguigu.rabbitmq.five;
import com.atguigu.rabbitmq.utils.RabbitMqUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class ReceiveLogs02 {
private static final String EXCHANGE_NAME="logs";
public static void main(String[] args) throws Exception {
Channel channel = RabbitMqUtils.getChannel();
channel.exchangeDeclare(EXCHANGE_NAME,"fanout");
/**
* 生产一个临时的队列,队列的名称是随机的
* 当消费者断开和该队列的连接时i,队列自动删除
*/
String queueName = channel.queueDeclare().getQueue();
//把该临时队列绑定我们的exchage 其中routingkey(也称之为bingding key)为空字符串
channel.queueBind(queueName,EXCHANGE_NAME,"");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
File file = new File("C:\\work\\rabbitmq_info.txt");
FileUtils.writeStringToFile(file,message,"UTF-8");
System.out.println("数据写入文件成功");
};
channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });
}
}