从Spring Boot教程开始:https : //spring.io/guides/gs/messaging- rabbitmq/
他们给出了仅创建1个队列和1个队列的示例,但是,如果我希望能够创建多于1个队列,该怎么办?怎么可能呢?
显然,我不能两次创建相同的bean:
@Bean Queue queue() { return new Queue(queueNameAAA, false); } @Bean Queue queue() { return new Queue(queueNameBBB, false); }
您不能两次创建相同的bean,它将使模棱两可。
为bean定义工厂方法指定不同的名称。通常,按照约定,您将它们命名为与队列相同的名称,但这不是必需的…
@Bean Queue queue1() { return new Queue(queueNameAAA, false); } @Bean Queue queue2() { return new Queue(queueNameBBB, false); }
方法名称是bean名称。
编辑
在绑定bean中使用队列时,有两种选择:
@Bean Binding binding1(@Qualifier("queue1") Queue queue, TopicExchange exchange) { return BindingBuilder.bind(queue).to(exchange).with(queueNameAAA); } @Bean Binding binding2(@Qualifier("queue2") Queue queue, TopicExchange exchange) { return BindingBuilder.bind(queue).to(exchange).with(queueNameBBB); }
要么
@Bean Binding binding1(TopicExchange exchange) { return BindingBuilder.bind(queue1()).to(exchange).with(queueNameAAA); } @Bean Binding binding2(TopicExchange exchange) { return BindingBuilder.bind(queue2()).to(exchange).with(queueNameBBB); }
甚至更好…
@Bean Binding binding1(TopicExchange exchange) { return BindingBuilder.bind(queue1()).to(exchange).with(queue1().getName()); } @Bean Binding binding2(TopicExchange exchange) { return BindingBuilder.bind(queue2()).to(exchange).with(queue2().getName()); }