我正在尝试创建一个扇出交换,每个人都会收到来自发布者的消息。我的问题是,侦听器无法获取队列中发布的消息。设置的队列都是与应用程序实例一起消亡的匿名队列。出版商&订阅者在同一个应用程序中。非常感谢任何帮助。
队列配置:
@Value("${apcp.rabbitmq.refresh-exchange}")
private String fanoutExchangeName;
@Autowired
Queue anonQueue;
@Bean("amqp-admin")
@PostConstruct
public AmqpAdmin AMQPAdmin(){
log.info(connectionFactory.toString());
AmqpAdmin amqpAdmin = new RabbitAdmin(connectionFactory);
return amqpAdmin;
}
@Bean
@PostConstruct
public String initRefreshAmqp(){
setupFanOutExchange();
return "";
}
public void setupFanOutExchange(){
AmqpAdmin amqpAdmin = new RabbitAdmin(connectionFactory);
FanoutExchange exchange = new FanoutExchange(fanoutExchangeName);
amqpAdmin.declareExchange(exchange);
Queue queue = new Queue(anonQueue, false, true, true);
amqpAdmin.declareQueue(queue);
amqpAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange));
}
出版商
@RequestMapping(value = "/publish")
public String publish(String message){
rabbitTemplate.convertAndSend(exchangeName, message);
return "";
}
订户配置
@Bean
@PostConstruct
public SimpleRabbitListenerContainerFactory listenerFactory() {
log.info("CONNECTIONS:"+connectionFactory.toString());
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setMessageConverter(jsonMessageConverter());
return factory;
}
订阅者监听器
@RabbitListener(queues = "#{anonQueue.name}", containerFactory = "listenerFactory")
public void receiverQueue(String message){
log.info(message);
}
答案 0 :(得分:1)
1)没有这样的方法:
rabbitTemplate.convertAndSend(exchangeName, message);
双方法是
public void convertAndSend(String routingKey, final Object object) throws AmqpException {
所以经纪人正在放弃你的消息。
2)您不得在bean定义
中调用管理方法(或执行涉及代理的任何事情)3)您的配置比需要的要复杂得多。
这很好......
@SpringBootApplication
public class So49854747Application {
public static void main(String[] args) {
SpringApplication.run(So49854747Application.class, args).close();
}
@Bean
public ApplicationRunner runner(RabbitTemplate template, FanoutExchange exchange) {
return args -> {
template.convertAndSend(exchange.getName(), "", "foo");
Thread.sleep(10_000);
};
}
@Bean
public Queue anonQueue() {
return new AnonymousQueue();
}
@Bean
public FanoutExchange exchange() {
return new FanoutExchange("so49854747");
}
@Bean
public Binding binding() {
return BindingBuilder.bind(anonQueue()).to(exchange());
}
@RabbitListener(queues = "#{anonQueue.name}")
public void listen(String in) {
System.out.println(in);
}
}
2018-04-16 09:01:54.620 INFO 50389 --- [ main] com.example.So49854747Application : Started So49854747Application in 1.407 seconds (JVM running for 1.909)
foo