Spring AMQP 响应来自 MessageListener 的 ReplyTo 队列

标签 spring rabbitmq amqp

如果我正在异步监听 Spring AMQP 消息,我该如何使用发送方提供的 ReplyTo 队列和关联 ID 进行响应?

    @Override
public void onMessage(Message message) {

    byte[] bytes = message.getBody();

    String body = new String (bytes);

    logger.info(application + " processing message: \n" + body);

    //some business logic

    //now I want to respond to the replyto queue with the correlation ID
    //rabbitTemplate.????

}

最佳答案

根据有用的反馈,这里是使用 Spring Messaging 的等效解决方案:

public void onMessage(Message message) {

//mock response body
String body = "{ \"processing\": \"123456789\"}";

//mock response properties
MessageProperties properties = new MessageProperties();
properties.setContentType(MediaType.APPLICATION_JSON.toString());
properties.setContentEncoding(StandardCharsets.UTF_8.name());       

//return the Correlation ID if present
if (message.getMessageProperties().getCorrelationId() != null) {

    properties.setCorrelationId(message.getMessageProperties().getCorrelationId());
}

//create and return the response message
Message responseMessage = new Message(body.getBytes(), properties);

rabbitTemplate.send(message.getMessageProperties().getReplyTo(), responseMessage);

logger.info("Processed and returned message");

对于刚接触 AMQP 的人来说,令人困惑的部分是知道回复消息属性是回复时的“路由键”值(send 或 convertAndSend 方法)。并且临时队列是在默认交换中创建的。对于需要相关 ID 的永久回复队列(临时回复队列不需要),情况并非总是如此。

关于Spring AMQP 响应来自 MessageListener 的 ReplyTo 队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35179796/

相关文章:

java - MyBatis 插入 null 时出现 nullPointerException

java - 导航菜单中不同帐户类型的不同菜单

java - 为什么我的 main 方法一直在运行?

python - 如何为 ActiveMQ 使用 AMQP python 客户端

rabbitmq - RabbitMQ队列消息

java - Spring Boot 嵌入式 HornetQ 集群不转发消息

java - Spring MVC 的问题。如何从两个或多个对象创建 View ?

java - 使用java停止队列监听RabbitMQ

django - 多个Django项目无意间接收到对方的celery任务

javascript - RabbitMQ。循环发布消息