Publish/Subscribe 发布与订阅:
通过交换机来实现,一个生产者可以让不同队列的消费者同时得到消息
生产者:
package Fanout;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import utils.RabbitMqUtils;
import java.io.IOException;
public class Provider {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMqUtils.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("logs","fanout");//创建交换机 1.交换机名称 2.交换机类型
channel.basicPublish("logs","",null,"hello exchanges".getBytes());
RabbitMqUtils.closeConnectionAndChannel(channel,connection);
}
}
多个消费者在不同的队列中:
消费者1:
package Fanout;
import com.rabbitmq.client.*;
import utils.RabbitMqUtils;
import java.io.IOException;
public class Consumer {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMqUtils.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("logs","fanout");//可以再次声名队列,有就调用 没有才创建 相当于绑定
String queueName = channel.queueDeclare().getQueue();//声名临时队列 不指定具体队列
// channel.exchangeBind("logs",queueName,"fanout");//绑定队列
channel.queueBind(queueName,"logs","");//1.队列名 2.交换机名 3.routing key
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));
}
});
}
}
消费者2:
package Fanout;
import com.rabbitmq.client.*;
import utils.RabbitMqUtils;
import java.io.IOException;
public class Consumer1 {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMqUtils.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("logs","fanout");//可以再次声名队列,有就调用 没有才创建 相当于绑定
String queueName = channel.queueDeclare().getQueue();//声名临时队列
// channel.exchangeBind("logs",queueName,"fanout");//绑定队列
channel.queueBind(queueName,"logs","");//1.队列名 2.交换机名 3.routing key
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("消费者3---"+new String(body));
}
});
}
}