RabbitMQ - 向队列中的特定消费者发送消息

RabbitMQ - Send message to a particular consumer in a queue

情况是这样的 - 有多个应用程序服务器。浏览器可以通过 websocket 连接到任何应用服务器。

应用程序服务器(消费者)都在侦听特定队列。一旦收到 Web 套接字连接,特定的应用程序服务器就会将队列与路由键 {userId} 绑定到直接交换。

我希望使用路由键 {userId} 发送到直接交换的消息仅由发生绑定的特定应用服务器接收。

在这种情况下,直接交换是否适合使用?还是应该使用其他类型的交换?

我正在使用 spring-amqp 在 websocket 进入时创建动态绑定

// create the RabbitMq queue and bind to it
String routingKey = MessageConstants.getRoutingKeyForUserRecommendationQueue(user);
Binding userRecommendationBinding = BindingBuilder.bind(userRecommendationsQueue).
    to(directExchange).with(routingKey);
amqpAdmin.declareBinding(userRecommendationBinding);

其实你走对了路。

是的:通过适当的绑定直接交换应该可以节省您的时间。

在 RabbitMQ 教程中查看更多信息:http://www.rabbitmq.com/tutorials/tutorial-four-java.html

另请查看有关此事的 Spring AMQP 样本:https://github.com/spring-projects/spring-amqp-samples/tree/master/rabbitmq-tutorials

更新

Unfortunately that is not what is happening. The messages seem to go randomly to any consumer, and not just the consumer that created the binding.

嗯嗯嗯。这是可能的,因为我们只路由我的key,但之后消息被放入队列,该队列可能有多个消费者在不同的机器上。

在这种情况下是:动态绑定没有帮助。

您应该考虑创建一个独特的新队列(自动删除没问题)并从中准确绑定和监听。 SimpleMessageListenerContainer 支持在运行时 addQueues() 为新队列启动新消费者。

我认为这对你有用。

您仍然不应该在生产者方面做任何事情:相同的 exhchangeroutingKey 逻辑。

Send message to a particular consumer in a queue

这是不可能的。连接到队列的任何消费者都有机会消费队列中的任何给定消息

I want a message sent to the direct exchange with the routing key {userId} to be received by only the particular app server where the binding has occured.

您可以通过为您的消费者创建 exclusive / autoDelete 队列来做到这一点,并使用一个绑定将该消费者的所有消息定向到该队列。

Is a direct exchange the right exchange to use in this case?

直接交流或者话题交流都可以。直接交流稍微容易理解,但是话题交流更灵活