1、 代码编写:
1、生产者代码:
public class Producer_PubSub {
public static void main(String[] args) throws IOException, TimeoutException {
ConnUtils cs = new ConnUtils();
Connection connection = cs.getConnection();
Channel channel = connection.createChannel();
String exchangeName = "test_fanout";
channel.exchangeDeclare(exchangeName, BuiltinExchangeType.FANOUT,true,false,false,null);
String queue1Name = "test_fanout_queue1";
String queue2Name = "test_fanout_queue2";
channel.queueDeclare(queue1Name,true,false,false,null);
channel.queueDeclare(queue2Name,true,false,false,null);
channel.queueBind(queue1Name,exchangeName,"");
channel.queueBind(queue2Name,exchangeName,"");
String body = "fanout test";
channel.basicPublish(exchangeName,"",null,body.getBytes());
channel.close();
connection.close();
}
}
2、消费者01代码:
public class Consumer_PubSub1 {
public static void main(String[] args) throws IOException, TimeoutException {
ConnUtils cs = new ConnUtils();
Connection connection = cs.getConnection();
Channel channel = connection.createChannel();
String queue1Name = "test_fanout_queue1";
channel.queueDeclare(queue1Name, true, false, false, null);
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("body:"+new String(body));
}
};
channel.basicConsume(queue1Name,true,consumer);
}
}
3、消费者02代码:
public class Consumer_PubSub2 {
public static void main(String[] args) throws IOException, TimeoutException {
ConnUtils cs = new ConnUtils();
Connection connection = cs.getConnection();
Channel channel = connection.createChannel();
String queue2Name = "test_fanout_queue2";
channel.queueDeclare(queue2Name, true, false, false, null);
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("body:"+new String(body));
}
};
channel.basicConsume(queue2Name,true,consumer);
}
}
2、测试
rm控制页面:
![在这里插入图片描述](https://img-blog.csdnimg.cn/9c94312e0a3742eba44c3d505e78c852.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBARWNob0J5Q29kZQ==,size_20,color_FFFFFF,t_70,g_se,x_16)
消费者01控制台:
body:fanout test
消费者02控制台:
body:fanout test
项目代码链接:https://github.com/Mbm7280/rabbitmq_demo