Provicer
public class Provider {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtil.getConnection();
Channel channel = connection.createChannel();
//通道声明交换机 参数1:交换机名称(不存在则创建) 参数2:交换机类型 fanout:广播类型
channel.exchangeDeclare("testForFanout","fanout");
//发送消息
channel.basicPublish("testForFanout","",null,"fanout".getBytes());
RabbitMQUtil.closeAll(channel,connection);
}
}
因为是广播模型,绑定同一个交换机的消费者就可以收到相同的消息,只是消费者的业务处理可能不同,因此简略,此处只有一个消费者
public class Consumer1 {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtil.getConnection();
Channel channel = connection.createChannel();
//通道绑定交换机
channel.exchangeDeclare("testForFanout","fanout");
//临时队列
String queue = channel.queueDeclare().getQueue();
//绑定交换机和队列
channel.queueBind(queue,"testForFanout","");
//消费消息
channel.basicConsume(queue,true,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者1:"+ new String(body));
}
});
}
}