发送流程
可以有多个消费者
每个消费者有自己的对列
每个对列都要绑定到Excheang交换机
生产者只能把消息发送到交换机,交换机决定把消息广播到那些对列,生产者无法决定
对列的消费者都能拿到消息,实现一条消息被多个消费者消费
生产者
package com.huixiang.rabbitmq.fanout;
import com.huixiang.utils.RabbitmqUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
public class Productor {
public static void main(String[] args) {
Connection connection = null;
Channel channel = null;
try {
connection = RabbitmqUtils.setConnection();
channel = connection.createChannel();
String queueName = "queueName1";
channel.exchangeDeclare("logs","fanout");
for (int i =0;i<10;i++){
channel.basicPublish("logs","",null,"nihao".getBytes());
}
}catch (Exception e){
e.printStackTrace();
}finally {
RabbitmqUtils.closeConnectionChanel(channel,connection);
}
}
}
消费者
package com.huixiang.rabbitmq.fanout;
import com.huixiang.utils.RabbitmqUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer1 {
public static void main(String[] args) {
Connection connection = null;
Channel channel = null;
try {
connection = RabbitmqUtils.setConnection();
channel = connection.createChannel();
channel.exchangeDeclare("logs","fanout");
String queue = channel.queueDeclare().getQueue();
channel.queueBind(queue,"logs","");
channel.basicConsume(queue, true, new DeliverCallback() {
@Override
public void handle(String consumerTag, Delivery message) throws IOException {
System.out.println("消费者1:收到消息" + new String(message.getBody(), "UTF-8"));
}
}, new CancelCallback() {
@Override
public void handle(String consumerTag) throws IOException {
System.out.println("失败");
}
});
}catch (Exception e){
e.printStackTrace();
}
}
}