3.发布/订阅模式
发布/订阅模式和工作模式最大的不同是,发布/订阅模式才真正的引入Exchange概念,并且采用的fanout交换机(此处自行复习Exchange的四种类型)
生产者:
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
* @ClassName : Publisher
* @Description : TODO
* @Author : Becolette
* @Date: 2020/9/27 23:08
*/
public class Publisher {
private static final String EXCHANGE_NAME = "logs";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
try (Channel channel = connection.createChannel()) {
/**
* @param exchange the name of the exchange
* 交换机名称
* @param type the exchange type
* 交换机类型
*/
channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
String message = argv.length < 1 ? "info: Hello World!" : String.join(" ", argv);
/**
* @param exchange the exchange to publish the message to
* 交换机
* @param routingKey the routing key
* 连接键
* @param props other properties for the message - routing headers etc
* 消息其他属性
* @param body the message body
* 消息体
*/
channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + message + "'");
}
}
}
消费者(可以多建立几个,此处我只写了一个):
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
/**
* @ClassName : Subscriber
* @Description : 消费者
* @Author : Becolette
* @Date: 2020/9/27 23:09
*/
public class Subscriber {
private static final String EXCHANGE_NAME = "logs";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
/**
* 由于交换机采用的是群发,也就是广播的形式,所以自动生成queue
* 并声明binding
*/
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, EXCHANGE_NAME, "");
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
};
channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {
});
}
}