Sringboot整合RabbitMQ(三):发布订阅

139 阅读1分钟
先创建一个 fanout 类型的交换器,命名为”tut.fanout”
@Profile({"tut3", "pub-sub"})
@Configuration
public class Tut3Config {

 /**
     * 定义一个 Exchange
     *
     * @return FanoutExchange
     */
     @Bean
    public FanoutExchange queue() {
        return new FanoutExchange("tut.fanout");
    }

    /**
     * 消费者一端的配置:queues、bindings
     */
    @Profile("receiver")
    private static class ReceiverConfig {

        @Bean 
        public Queue autoDeleteQueue1() {
            return new AnonymousQueue();
        }

        @Bean 
        public Queue autoDeleteQueue2() {
            return new AnonymousQueue();
        }

        @Bean 
        public Binding binding1(FanoutExchange fanout, Queue autoDeleteQueue1) {
            return BindingBuilder.bind(autoDeleteQueue1).to(fanout);
        }

        @Bean 
        public Binding binding2(FanoutExchange fanout, Queue autoDeleteQueue2) {
            return BindingBuilder.bind(autoDeleteQueue2).to(fanout);
        }

        @Bean 
        public Tut3Receiver receiver() {
            return new Tut3Receiver();
        }

    }

    
@Bean 
@Profile("sender")
    public Tut3Sender sender() {
        return new Tut3Sender();
    }

}

我们定义了两个 profiles(tut3、pub-sub)以保证我们能运行指定的示例。然后创建了一个消费者端的配置,并在其中定义了两个 AnonymousQueue 和两个 Binding 以便将相应的队列和交换器绑定起来。

交换器列表
rabbitmqctl 能够列出服务器上所有的交换器。这个列表中有一些叫做 amq.* 的交换器。这些都是默认创建的,不过这时候你还不需要使用他们,了解springcloud架构可以加求求:三五三六二四七二五九