RabbitMQ04_fanout广播模型

x33g5p2x  于2021-12-19 转载在 其他  
字(1.8k)|赞(0)|评价(0)|浏览(570)

RabbitMQ04_fanout广播模型

生产者发送消息给交换机(Exchange)
交换机将消息发送给所有绑定的队列
队列的消费者都能拿到消息,实现了一条消息被多个消费者消费

消息生产者:

  1. public static void main(String[] args) throws IOException {
  2. Connection connection = RabbitMQUtils.getConnection();
  3. Channel channel = connection.createChannel();
  4. //将通道声明指定的交换机
  5. //参数1:交换机名称(自定义) 参数2:交换机的类型 fanout表示广播类型
  6. channel.exchangeDeclare("logs", "fanout");
  7. //发送消息给交换机
  8. //参数2:在广播模型中routingKey没有意义,填空字符串
  9. channel.basicPublish("logs", "", null, "fanout type message".getBytes());
  10. RabbitMQUtils.closeConnectionAndChannel(channel, connection);
  11. }

消费者1:

  1. public static void main(String[] args) throws IOException {
  2. Connection connection = RabbitMQUtils.getConnection();
  3. Channel channel = connection.createChannel();
  4. //通道绑定交换机
  5. channel.exchangeDeclare("logs", "fanout");
  6. //创建临时队列
  7. String queueName = channel.queueDeclare().getQueue();
  8. //绑定交换机和队列,参数3:routingKey在fanout中无意义
  9. channel.queueBind(queueName, "logs", "");
  10. //消费消息
  11. channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
  12. @Override
  13. public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
  14. throws IOException {
  15. System.out.println("消费者1:"+new String(body));
  16. }
  17. });
  18. }

消费者2:

  1. public static void main(String[] args) throws IOException {
  2. Connection connection = RabbitMQUtils.getConnection();
  3. Channel channel = connection.createChannel();
  4. channel.exchangeDeclare("logs", "fanout");
  5. String queueName = channel.queueDeclare().getQueue();
  6. channel.queueBind(queueName, "logs", "");
  7. channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
  8. @Override
  9. public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
  10. throws IOException {
  11. System.out.println("消费者2:"+new String(body));
  12. }
  13. });
  14. }

每当消息生产者生产消息时,消费者1和消费者2都能够消费消息,这就是广播模式

相关文章