【发布时间】:2016-05-11 08:17:11
【问题描述】:
我正在使用 Spring-AMQP rabbitmq 实现测试请求/响应模式,但我无法让它工作......
我已经配置了以下工件:
test_exchange 与问候队列。路由键 = 问候
reply_exchange 与回复队列。路由键 = 回复
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory =
new CachingConnectionFactory("....IP of broker...");
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
return connectionFactory;
}
@Bean
public Queue greeting() {
return new Queue("greeting");
}
@Bean
public Queue replies() {
return new Queue("replies");
}
MessageListener receiver() {
return new MessageListenerAdapter(new RabbitMqReceiver(), "onMessage");
}
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, Queue replies) {
RabbitTemplate template = new RabbitTemplate(connectionFactory);
template.setExchange("test_exchange");
template.setRoutingKey("greeting");
template.setReplyAddress("reply_exchange"+"/"+replies.getName());
template.setReplyTimeout(60000);
return template;
}
@Bean
public SimpleMessageListenerContainer replyContainer(ConnectionFactory connectionFactory,
RabbitTemplate rabbitTemplate, Queue replies) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setMessageListener(rabbitTemplate);
container.setQueues(replies);
return container;
}
@Bean
public SimpleMessageListenerContainer serviceListenerContainer(
ConnectionFactory connectionFactory) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueues(greeting());
container.setMessageListener(receiver());
return container;
}
我在 github 上关注示例,但它崩溃了:
原因:java.lang.IllegalStateException: RabbitTemplate 未配置为 MessageListener - 不能使用“replyAddress”:reply_exchange/replies
文档说:
从 1.5 版开始,RabbitTemplate 将检测它是否已配置为 MessageListener 以接收回复。否则,尝试发送和接收带有回复地址的消息将失败并返回 IllegalStateException(因为永远不会收到回复)。
这很好,但是 RabbitTemplate 是如何做到的呢?它如何检测是否配置为 MessageListener?
提前致谢
PS:发送代码:
public void send() {
Message message = MessageBuilder.withBody("Payload".getBytes())
.setContentType("text/plain")
.build();
Message reply = this.template.sendAndReceive(message);
System.out.println("Reply from server is: "+new String(reply.getBody()));
}
【问题讨论】: