POJO:
public class PojoListener {
public String handleMessage(String foo) {
System.out.println("IN MESSAGE RECEIVER!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
return foo.toUpperCase();
}
}
配置:
@Configuration
public class FixedReplyQueueConfig {
@Bean
public ConnectionFactory rabbitConnectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setHost("localhost");
connectionFactory.setUsername("urbanbuz");
connectionFactory.setPassword("ub");
connectionFactory.setVirtualHost("urbanbuzvhost");
return connectionFactory;
}
/**
* @return Rabbit template with fixed reply queue.
*/
@Bean
public RabbitTemplate fixedReplyQRabbitTemplate() {
RabbitTemplate template = new RabbitTemplate(rabbitConnectionFactory());
template.setExchange(ex().getName());
template.setRoutingKey("test");
template.setReplyQueue(replyQueue());
return template;
}
/**
* @return The reply listener container - the rabbit template is the listener.
*/
@Bean
public SimpleMessageListenerContainer replyListenerContainer() {
SimpleMessageListenerContainer container = new SimpleMe ssageListenerContainer();
container.setConnectionFactory(rabbitConnectionFactory());
container.setQueues(replyQueue());
container.setMessageListener(fixedReplyQRabbitTemplate());
return container;
}
/**
* @return The listener container that handles the request and returns the reply.
*/
@Bean
public SimpleMessageListenerContainer serviceListenerContainer() {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(rabbitConnectionFactory());
container.setQueues(requestQueue());
container.setMessageListener(new MessageListenerAdapter(new PojoListener()));
return container;
}
/**
* @return a non-durable auto-delete exchange.
*/
@Bean
public DirectExchange ex() {
return new DirectExchange("ub.exchange", false, true);
}
@Bean
public Binding binding() {
return BindingBuilder.bind(requestQueue()).to(ex()).with("test");
}
/**
* @return an anonymous (auto-delete) queue.
*/
@Bean
public Queue requestQueue() {
return new Queue("ub.request");
}
/**
* @return an anonymous (auto-delete) queue.
*/
@Bean
public Queue replyQueue() {
return new Queue("ub.reply");
}
/**
* @return an admin to handle the declarations.
*/
@Bean
public RabbitAdmin admin() {
return new RabbitAdmin(rabbitConnectionFactory());
}
}
使用main方法调用:
public class App {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(FixedReplyQueueConfig.class);
RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
String response = (String) rabbitTemplate.convertSendAndReceive("yalla");
System.out.println("response" + response);
}
}
我有两个问题:
当我运行此操作时,我收到以下错误:RabbitTemplate [错误]虽然我看到两个队列都收到了消息,但没有回复相关标题。
第二个问题是如何在不发送消息的情况下运行消费者代码(监听器)(因为最终调用者不会是我的java代码)?
答案 0 :(得分:0)
看起来它基于框架测试用例,这显然有用。
您是否正在向ub.reply发送任何其他消息?它是空的吗?
获取该日志消息的唯一方法是模板是否收到没有正确填充的相关ID属性的回复。
您只需运行应用程序并删除所有客户端代码,容器就会侦听入站请求。