RabbitMQ(三)——Publish/Subscribe

来源:互联网 发布:石油天然气文献数据库 编辑:程序博客网 时间:2024/06/06 18:46

发布/订阅
把一个消息交付给多个消费者
中间的x就是交换机
exchange有以下几种类型:

direct   根据 routingKey(路由键) 来分发消息到不同的队列中headers 通过键值对来匹配,可以定义为map匹配,有两种方式allany(不常用)fanout 把消息发给绑定给它的全部队列topic 是RabbitMQ中最灵活的一种方式,可以根据routing_key自由的绑定不同的队列

Topic Exchange

这里写图片描述
配置路由
这里注册了两个队列,hi和hello,并定义了路由规则,hello队列的toutingKey是“hello”,而hi队列匹配所有。

@Configurationpublic class RabbitConfig {    @Bean//注册一个,hello是队列名称,简单的    public Queue helloQueue() {        return new Queue("hello");    }    @Bean    public Queue hiQueue() {        return new Queue("hi");    }    @Bean    TopicExchange exchange() {        return new TopicExchange("exchange");    }    @Bean    Binding bindingExchangeMessage(Queue helloQueue, TopicExchange exchange) {        return BindingBuilder.bind(helloQueue).to(exchange).with("hello");    }    @Bean    Binding bindingExchangeMessages(Queue hiQueue, TopicExchange exchange) {        return BindingBuilder.bind(hiQueue).to(exchange).with("*");    }}

定义发送者

  public void send1(int i) {        String context = i+"hi";        System.out.println("Sender : " + context);        this.rabbitTemplate.convertAndSend("exchange", "hi", context);    }    public void send2(int i) {        String context = i+"hello";        System.out.println("Sender : " + context);        this.rabbitTemplate.convertAndSend("exchange", "hello", context);    }

定义接收者
定义一个hi队列的接收者

@Component@RabbitListener(queues = "hi")public class Receiver2 {    @RabbitHandler    public void process(String hi) {        System.out.println("Receiverhi  : " + hi);    }}

定义一个hello队列的接收者

@Component@RabbitListener(queues = "hello")public class Receiver {    @RabbitHandler    public void process(String hello) {        System.out.println("Receiverhello  : " + hello);    }}

测试:
当用send1发送时,仅hi接收到消息,而通过send2发送,两个队列都会匹配到

Fanout Exchange
给Fanout交换机发送消息,绑定了这个交换机的所有队列都收到这个消息。
配置路由

@Configurationpublic class RabbitConfig {    @Bean//注册一个,hello是队列名称,简单的    public Queue helloQueue() {        return new Queue("hello");    }    @Bean    public Queue hiQueue() {        return new Queue("hi");    }    /**     * fanout     * @return     */    @Bean    FanoutExchange fanoutExchange() {        return new FanoutExchange("fexchange");    }    @Bean    Binding bindingExchangeA(Queue helloQueue,FanoutExchange fexchange) {        return BindingBuilder.bind(helloQueue).to(fexchange);    }    @Bean    Binding bindingExchangeB(Queue hiQueue, FanoutExchange fexchange) {        return BindingBuilder.bind(hiQueue).to(fexchange);    }}

添加send

 public void send3(int i) {        String context = i+"hi ";        System.out.println("Sender : " + context);        this.rabbitTemplate.convertAndSend("fexchange","", context);    }

测试:不管routingKey写什么,都会匹配到,接收者会均匀接收