4.路由模式
路由模式与发布订阅模式的区别:
1.路由模式的routeKey是需要定义的
2.Exchange交换机的类型是有区别的,可以在枚举类BuiltinExchangeType中找到
3.一个是广播方式,一个是定向传送
另外:
1.接收者要先于发送者启动,否则接受不到消息(这个我还不知道为什么,待后面了解了再记录)
2.如果写了多个交换机,名称记得不要重复,否则报错
Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method
生产者:
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
* @ClassName : Publisher
* @Description : 生产者
* @Author : Becolette
* @Date: 2020/9/27 23:08
*/
public class RoutingSent {
private static final String EXCHANGE_NAME = "direct_exchange";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
/**
* @param exchange the name of the exchange
* 交换机名称
* @param type the exchange type
* 交换机类型
*/
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
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, "routing", null, message.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + message + "'");
}
}
消费者:
import com.rabbitmq.client.*;
/**
* @ClassName : Subscriber
* @Description : 消费者
* @Author : Becolette
* @Date: 2020/9/27 23:09
*/
public class RoutingRecv {
private static final String EXCHANGE_NAME = "direct_exchange";
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, BuiltinExchangeType.DIRECT);
/**
* 由于交换机采用的是群发,也就是广播的形式,所以自动生成queue
* 并声明binding
*/
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, EXCHANGE_NAME, "routing");
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 -> {
});
}
}