You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring AMQP:Amqp.outboundAdapter无reply-to致响应发送失败

问题分析与解决方案

核心问题根源

你遇到的报错并非convertAndSend的路由键被忽略,而是应用2的@RabbitListener方法返回了非void类型的结果,触发了Spring AMQP的自动回复逻辑——但应用1发送的原始消息没有携带reply-to属性,且未配置默认响应交换,导致自动回复无法找到目标地址,抛出异常。


解决方案

方案1:关闭自动回复,保留手动发送逻辑

修改应用2的监听方法为void返回类型,这样Spring AMQP不会触发自动回复,手动调用的convertAndSend会正常生效:

@RabbitListener(queues={"app1-to-2"})
public void handleMessage(final MyRequest request) {
    var myResponse = this.process(request);
    // 第一个参数为交换名称,使用默认交换则传空字符串
    rabbitTemplate.convertAndSend("", "app2-to-1", myResponse);
}

方案2:给应用1的消息添加reply-to属性,启用自动回复

在应用1的Spring Integration流中,通过Amqp.outboundAdapter为发送的消息设置reply-to属性,指向应用2的回复队列app2-to-1,这样应用2的方法返回值会自动发送到该队列:

  • 应用1的配置:
Amqp.outboundAdapter(rabbitTemplate)
    .routingKey("app1-to-2")
    .headers(headerSpec -> headerSpec.put("replyTo", "app2-to-1"));
  • 应用2的方法可简化为直接返回结果,无需手动调用convertAndSend:
@RabbitListener(queues={"app1-to-2"})
public MyResponse handleMessage(final MyRequest request) {
    return this.process(request);
}

方案3:配置默认响应交换(适合统一回复规则场景)

在应用2的RabbitTemplate中设置默认的回复地址,当消息无reply-to属性时,自动使用该配置发送回复:

@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
    RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
    // 指定默认回复的队列(基于默认交换)
    rabbitTemplate.setDefaultReplyRoutingKey("app2-to-1");
    rabbitTemplate.setDefaultReplyExchange("");
    return rabbitTemplate;
}

内容的提问来源于stack exchange,提问作者Christoph Dahlen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 07:55:42