RabbitMQ 教程 - 路由
路由
(使用 Spring AMQP)
前提条件
本教程假设您已安装并运行 RabbitMQ 在 localhost
的 标准端口 (5672) 上。如果您使用不同的主机、端口或凭据,则连接设置可能需要调整。
在哪里获得帮助
如果您在学习本教程时遇到问题,可以通过 GitHub Discussions 或 RabbitMQ 社区 Discord 联系我们。
在之前的教程中,我们构建了一个简单的 fanout exchange。我们能够将消息广播到多个接收者。
在本教程中,我们将为其添加一个功能 - 我们将使其能够仅订阅消息的子集。例如,我们将能够仅将消息定向到感兴趣的特定颜色(“橙色”、“黑色”、“绿色”),同时仍然能够在控制台上打印所有消息。
绑定
在之前的示例中,我们已经创建了绑定。您可能还记得我们在 Tut3Config
文件中使用了类似这样的代码
@Bean
public Binding binding1(FanoutExchange fanout,
Queue autoDeleteQueue1) {
return BindingBuilder.bind(autoDeleteQueue1).to(fanout);
}
绑定是交换机和队列之间的关系。可以简单地理解为:队列对来自该交换机的消息感兴趣。
绑定可以接受额外的 binding key 参数。Spring AMQP 使用流畅的 API 使这种关系非常清晰。我们将交换机和队列传入 BindingBuilder
,然后简单地将队列“绑定到”交换机,“使用 binding key”,如下所示
@Bean
public Binding binding1a(DirectExchange direct,
Queue autoDeleteQueue1) {
return BindingBuilder.bind(autoDeleteQueue1)
.to(direct)
.with("orange");
}
binding key 的含义取决于交换机类型。我们之前使用的 fanout
exchanges 只是忽略了它的值。
Direct exchange
我们之前教程中的消息传递系统将所有消息广播给所有消费者。我们想要扩展它,以允许根据消息的颜色类型过滤消息。例如,我们可能希望一个将日志消息写入磁盘的程序只接收关键错误,而不是在警告或信息日志消息上浪费磁盘空间。
我们之前使用的是 fanout
exchange,它没有给我们太多的灵活性 - 它只能进行盲目的广播。
我们将改用 direct
exchange。direct
exchange 背后的路由算法很简单 - 消息会发送到 binding key 与消息的 routing key 完全匹配的队列。
为了说明这一点,请考虑以下设置
在此设置中,我们可以看到 direct
exchange X
,其中绑定了两个队列。第一个队列使用 binding key orange
绑定,第二个队列有两个绑定,一个使用 binding key black
,另一个使用 green
。
在这样的设置中,发布到交换机的 routing key 为 orange
的消息将被路由到队列 Q1
。routing key 为 black
或 green
的消息将发送到 Q2
。所有其他消息将被丢弃。
多个绑定
使用相同的 binding key 绑定多个队列是完全合法的。在我们的示例中,我们可以添加一个 X
和 Q1
之间的绑定,使用 binding key black
。在这种情况下,direct
exchange 的行为将类似于 fanout
,并将消息广播到所有匹配的队列。routing key 为 black
的消息将被传递到 Q1
和 Q2
。
发布消息
我们将使用此模型作为我们的路由系统。我们将把消息发送到 direct
exchange 而不是 fanout
。我们将提供颜色作为 routing key。这样,接收程序将能够选择它想要接收(或订阅)的颜色。让我们首先关注发送消息。
与往常一样,我们在 Tut4Config
中进行一些 Spring Boot 配置
@Bean
public DirectExchange direct() {
return new DirectExchange("tut.direct");
}
我们已准备好发送消息。如图所示,颜色可以是“橙色”、“黑色”或“绿色”之一。
订阅
接收消息的工作方式与之前的教程类似,但有一个例外 - 我们将为我们感兴趣的每种颜色创建一个新的绑定。这也将在 Tut4Config
中进行配置
@Bean
public DirectExchange direct() {
return new DirectExchange("tut.direct");
}
...
@Bean
public Binding binding1a(DirectExchange direct,
Queue autoDeleteQueue1) {
return BindingBuilder.bind(autoDeleteQueue1)
.to(direct)
.with("orange");
}
整合在一起
与之前的教程一样,为本教程创建一个名为 tut4
的新包,并创建 Tut4Config
类。Tut4Config.java
类的代码
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Profile({"tut4","routing"})
@Configuration
public class Tut4Config {
@Bean
public DirectExchange direct() {
return new DirectExchange("tut.direct");
}
@Profile("receiver")
private static class ReceiverConfig {
@Bean
public Queue autoDeleteQueue1() {
return new AnonymousQueue();
}
@Bean
public Queue autoDeleteQueue2() {
return new AnonymousQueue();
}
@Bean
public Binding binding1a(DirectExchange direct,
Queue autoDeleteQueue1) {
return BindingBuilder.bind(autoDeleteQueue1)
.to(direct)
.with("orange");
}
@Bean
public Binding binding1b(DirectExchange direct,
Queue autoDeleteQueue1) {
return BindingBuilder.bind(autoDeleteQueue1)
.to(direct)
.with("black");
}
@Bean
public Binding binding2a(DirectExchange direct,
Queue autoDeleteQueue2) {
return BindingBuilder.bind(autoDeleteQueue2)
.to(direct)
.with("green");
}
@Bean
public Binding binding2b(DirectExchange direct,
Queue autoDeleteQueue2) {
return BindingBuilder.bind(autoDeleteQueue2)
.to(direct)
.with("black");
}
@Bean
public Tut4Receiver receiver() {
return new Tut4Receiver();
}
}
@Profile("sender")
@Bean
public Tut4Sender sender() {
return new Tut4Sender();
}
}
我们的发送者类的代码是
package org.springframework.amqp.tutorials.tut4;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.concurrent.atomic.AtomicInteger;
public class Tut4Sender {
@Autowired
private RabbitTemplate template;
@Autowired
private DirectExchange direct;
AtomicInteger index = new AtomicInteger(0);
AtomicInteger count = new AtomicInteger(0);
private final String[] keys = {"orange", "black", "green"};
@Scheduled(fixedDelay = 1000, initialDelay = 500)
public void send() {
StringBuilder builder = new StringBuilder("Hello to ");
if (this.index.incrementAndGet() == 3) {
this.index.set(0);
}
String key = keys[this.index.get()];
builder.append(key).append(' ');
builder.append(this.count.get());
String message = builder.toString();
template.convertAndSend(direct.getName(), key, message);
System.out.println(" [x] Sent '" + message + "'");
}
}
Tut4Receiver.java
的代码是
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.util.StopWatch;
public class Tut4Receiver {
@RabbitListener(queues = "#{autoDeleteQueue1.name}")
public void receive1(String in) throws InterruptedException {
receive(in, 1);
}
@RabbitListener(queues = "#{autoDeleteQueue2.name}")
public void receive2(String in) throws InterruptedException {
receive(in, 2);
}
public void receive(String in, int receiver) throws InterruptedException {
StopWatch watch = new StopWatch();
watch.start();
System.out.println("instance " + receiver + " [x] Received '" + in + "'");
doWork(in);
watch.stop();
System.out.println("instance " + receiver + " [x] Done in " +
watch.getTotalTimeSeconds() + "s");
}
private void doWork(String in) throws InterruptedException {
for (char ch : in.toCharArray()) {
if (ch == '.') {
Thread.sleep(1000);
}
}
}
}
照常编译(有关 Maven 编译和从 jar 执行选项的信息,请参阅教程一)。
./mvnw clean package
在一个终端窗口中,您可以运行
java -jar target/rabbitmq-tutorials.jar \
--spring.profiles.active=routing,receiver \
--tutorial.client.duration=60000
在另一个终端窗口中运行发送者
java -jar target/rabbitmq-tutorials.jar \
--spring.profiles.active=routing,sender \
--tutorial.client.duration=60000
Tut4Receiver.java 源代码 和 Tut4Sender.java 源代码的完整源代码。配置位于 Tut4Config.java 源代码中。
继续教程 5,了解如何根据模式监听消息。