广播模型
生产者将消息发送给交换机,交换机发送消息到消息队列。
消息发送流程:
可以有多个消费者
每个消费者都有自己的队列
每个队列都需要绑定自己的交换机
生产者发送的消息,只能发送到交换机,交换机决定要发给那个队列
交换机把消息发送给绑定过的所有队列
队列的消费者都能拿到消息,实现一条消息被多个消费者消费。
对于生产者来说,他只需要将消息发送给交换机。
示例代码
package com.baizhi.fanout;
import com.baizhi.Utils.rabbitmqUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
public class Provider {
public static void main(String[] args) {
Connection connection= rabbitmqUtils.getConnection();
try {
Channel channel=connection.createChannel();
//声明交换机,参数一交换机名称,参数二交换机类型
channel.exchangeDeclare("regist", "fanout");
//发送消息
//参数一交换机名称,参数二路由信息,参数三持久化,参数四具体消息名称
channel.basicPublish("regist","", null, "fanout type message".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.baizhi.fanout;
import com.baizhi.Utils.rabbitmqUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Customer1 {
public static void main(String[] args) {
Connection connection= rabbitmqUtils.getConnection();
try {
Channel channel=connection.createChannel();
//通道绑定交换机
channel.exchangeDeclare("regist", "fanout");
//通道绑定队列,创建临时队列,没必要持久化
String queueName=channel.queueDeclare().getQueue();
//绑定交换机和队列
channel.queueBind(queueName, "regist", "");
channel.basicConsume(queueName, 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));
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.baizhi.fanout;
import com.baizhi.Utils.rabbitmqUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Customer2 {
public static void main(String[] args) {
Connection connection= rabbitmqUtils.getConnection();
try {
Channel channel=connection.createChannel();
//通道绑定交换机
channel.exchangeDeclare("regist", "fanout");
//通道绑定队列,创建临时队列,没必要持久化
String queueName=channel.queueDeclare().getQueue();
//绑定交换机和队列
channel.queueBind(queueName, "regist", "");
channel.basicConsume(queueName, true, new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者2"+new String(body));
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}