路由模式特点:
- 队列与交换机的绑定,不能是任意绑定了,而是要指定一个
RoutingKey
(路由key) - 消息的发送方在 向 Exchange发送消息时,也必须指定消息的
RoutingKey
。 - Exchange不再把消息交给每一个绑定的队列,而是根据消息的
Routing Key
进行判断,只有队列的Routingkey
与消息的Routing key
完全一致,才会接收到消息
说明:
- P:生产者,向Exchange发送消息,发送消息时,会指定一个routing key。
- X:Exchange(交换机),接收生产者的消息,然后把消息递交给 与routing key完全匹配的队列
- C1:消费者,其所在队列指定了需要routing key 为 error 的消息
- C2:消费者,其所在队列指定了需要routing key 为 info、error、warning 的消息
在编码上 路由模式(Routing) 与
Publish/Subscribe发布与订阅模式
的区别是:
(1)交换机的类型为 Direct
(2)队列绑定交换机的时需要指定 routing key
一、生产者Module
(1)pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>rabbitmq-demo</artifactId>
<groupId>net.xiaof</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>rabbitmq-producer</artifactId>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--rabbitmq java 客户端-->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.6.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
(2)生产者类
package net.xiaof.producer;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* @author zhangxh
* @Description: 生产者(路由模式)
* @date 2020-12-16
*/
public class Producer_Routing {
public static void main(String[] args) throws IOException, TimeoutException {
//1.创建连接工厂,设置相关连接参数
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.116.161");
factory.setPort(5672);
factory.setVirtualHost("/myhost");
factory.setUsername("xiao");
factory.setPassword("xiao");
//2. 创建连接Connection
Connection connection = factory.newConnection();
//3. 创建Channel
Channel channel = connection.createChannel();
//4. 声明交换机exchange
/**
* 【API说明】:
* exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable, boolean autoDelete, boolean internal, Map<String, Object> arguments)
* 参数:
* (1)String exchange:交换机名称
* (2)BuiltinExchangeType type:交换机类型
* DIRECT("direct"):定向
* FANOUT("fanout"):扇形(广播),发送消息到每一个与之绑定队列。
* TOPIC("topic"):通配符的方式
* HEADERS("headers"):参数匹配
* (3)boolean durable:是否持久化
* (4)boolean autoDelete:是否自动删除
* (5)boolean internal:内部使用,一般用false
* (6)Map<String, Object> arguments:参数
*/
String exchangeName = "routing_direct_exchange";
channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, true, false, false, null);
//5. 声明队列Queue
/**
* 【API说明】:
* queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
* 参数:
* (1)String queue:队列名称。如果当前队列名称不存在,则会创建该队列,否则不会创建
* (2)boolean durable:是否持久化。即队列在服务器重启后是否还存在
* (3)boolean exclusive:是否独占。只能有一个消费者监听这队列;当Connection关闭时,是否删除队列
* (4)boolean autoDelete:是否自动删除。如果为true,至少有一个消费者连接到这个队列,之后所有与这个队列连接的消费者都断开时,队列会自动删除。
* (5)Map<String, Object> arguments:附带参数。队列的其他属性,例如:x-message-ttl、x-expires、x-max-length、x-maxlength-bytes、x-dead-letter-exchange、x-dead-letter-routing-key、x-max-priority
*/
String queueName1 = "routing_direct_queue1";
String queueName2 = "routing_direct_queue2";
channel.queueDeclare(queueName1, true, false, false, null);
channel.queueDeclare(queueName2, true, false, false, null);
//6. 绑定队列和交换机
/**
* 【API说明】:
* queueBind(String queue, String exchange, String routingKey)
* 参数:
* (1)String queue:队列名称。
* (2)String exchange:交换机名称
* (3)String routingKey:路由键,绑定规则(使用了routingKey时,发布消息方法basicPublish(...)也需要指定相关routingKey)
* 如果交换机的类型为fanout ,routingKey设置为""
* 如果交换机的类型为direct ,需要设置routingKey
*/
//队列1绑定 error
channel.queueBind(queueName1, exchangeName, "error");
//队列2绑定 info error warning
channel.queueBind(queueName2, exchangeName, "info");
channel.queueBind(queueName2, exchangeName, "warning");
channel.queueBind(queueName2, exchangeName, "error");
//7. 发布消息
/**
* 【API说明】:
* basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body)
* 参数:
* (1)String exchange:交换机名称。简单模式下交换机会使用默认的 ""
* (2)String routingKey:路由key
* (3)BasicProperties props:配置信息
* (4)byte[] body:发送消息数据
*/
String bodyMsg = "[info]日志信息:马云调用了add方法";
channel.basicPublish(exchangeName, "info", null, bodyMsg.getBytes());
//8. 关闭资源
channel.close();
connection.close();
}
}
二、消费者Module
(1)pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>rabbitmq-demo</artifactId>
<groupId>net.xiaof</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>rabbitmq-consumer</artifactId>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--rabbitmq java客户端-->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.6.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
(2)消费者类1
package net.xiaof.consumer;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* @author zhangxh
* @Description: 消费者1(路由模式)
* @date 2020-12-16
*/
public class Consumer_Routing1 {
public static void main(String[] args) throws IOException, TimeoutException {
//1.创建连接工厂,设置相关连接参数
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.116.161");
factory.setPort(5672);
factory.setVirtualHost("/myhost");
factory.setUsername("xiao");
factory.setPassword("xiao");
//2. 创建连接Connection
Connection connection = factory.newConnection();
//3. 创建Channel
Channel channel = connection.createChannel();
//4. 接收消息
Consumer consumer = new DefaultConsumer(channel) {
/**
* 回调方法,当收到消息后,会自动执行该方法
* void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
* 参数:
* (1)String consumerTag:标识
* (2)Envelope envelope:获取一些信息,交换机,路由key...
* (3)AMQP.BasicProperties properties:配置信息
* (4)byte[] body:数据
*/
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
// System.out.println("consumerTag:" + consumerTag);
// System.out.println("Exchange:" + envelope.getExchange());
// System.out.println("RoutingKey:" + envelope.getRoutingKey());
// System.out.println("properties:" + properties);
System.out.println("Consumer_Routing1.class");
System.out.println("body:" + new String(body));
}
};
/**
* 【API说明】:
* basicConsume(String queue, boolean autoAck, Consumer callback)
* 参数:
* (1)String queue:队列名称
* (2)boolean autoAck:是否自动确认
* (3)Consumer callback:回调对象
*/
String queueName1 = "routing_direct_queue1";
String queueName2 = "routing_direct_queue2";
channel.basicConsume(queueName1, true, consumer);//这里消费队列“pubsub_queue1”的消息
//5.关闭资源(消费者需要监听生产者消息,这里不关闭)
}
}
(3)消费者类2
package net.xiaof.consumer;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* @author zhangxh
* @Description: 消费者2(路由模式)
* @date 2020-12-16
*/
public class Consumer_Routing2 {
public static void main(String[] args) throws IOException, TimeoutException {
//1.创建连接工厂,设置相关连接参数
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.116.161");
factory.setPort(5672);
factory.setVirtualHost("/myhost");
factory.setUsername("xiao");
factory.setPassword("xiao");
//2. 创建连接Connection
Connection connection = factory.newConnection();
//3. 创建Channel
Channel channel = connection.createChannel();
//4. 接收消息
Consumer consumer = new DefaultConsumer(channel) {
/**
* 回调方法,当收到消息后,会自动执行该方法
* void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
* 参数:
* (1)String consumerTag:标识
* (2)Envelope envelope:获取一些信息,交换机,路由key...
* (3)AMQP.BasicProperties properties:配置信息
* (4)byte[] body:数据
*/
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
// System.out.println("consumerTag:" + consumerTag);
// System.out.println("Exchange:" + envelope.getExchange());
// System.out.println("RoutingKey:" + envelope.getRoutingKey());
// System.out.println("properties:" + properties);
System.out.println("Consumer_Routing2.class");
System.out.println("body:" + new String(body));
}
};
/**
* 【API说明】:
* basicConsume(String queue, boolean autoAck, Consumer callback)
* 参数:
* (1)String queue:队列名称
* (2)boolean autoAck:是否自动确认
* (3)Consumer callback:回调对象
*/
String queueName1 = "routing_direct_queue1";
String queueName2 = "routing_direct_queue2";
channel.basicConsume(queueName2, true, consumer);//这里消费队列“pubsub_queue1”的消息
//5.关闭资源(消费者需要监听生产者消息,这里不关闭)
}
}
三、测试
注意: 这里
第一次
需要先启动生产者类,队列的声明(创建),已经交给生产者,启动后,所声明队列会注册在RabbitMq的虚拟主机中,消费者只需要从指定的队列中消费消息即可。如果
第一次
先启动消费者,会报异常:找不到要消费的队列。
(1)先启动生产者类,生产者声明(创建)队列
在RabbitMQ的web管理端,查看队列情况:
(2)再分别启动 “消费者1 ” 和 “消费者2 ” 进行消费消息
关键代码:
运行结果:
(3)修改“生产者 ”代码如下
运行结果:
(4)在RabbitMQ的web管理端,查看路由绑定情况:
四、小结
Routing模式要求队列在绑定交换机时要指定routing key,消息会转发到符合routing key的队列。