springboot+rabbitmq两小时入门(四):fanout交换机

概要:

广播交换机,忽略routingkey,把所有发送到当前交换机的消息全部路由到所有与当前交换机绑定的队列中去。

 

application.properties配置:

spring.rabbitmq.host=localhost

# TCP/IP端口为5672,http端口为15672
spring.rabbitmq.port=5672

spring.rabbitmq.username=root

spring.rabbitmq.password=root

生产者:

package com.example.rabbitmq;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RabbitMQController {
    
    // 这里用的是RabbitTemplate发消息,也可以用AmqpTemplate,推荐使用RabbitTemplate。
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping(value = "/helloRabbit2")
    public String sendMQ2(){
        rabbitTemplate.convertAndSend("myExchange2", "","fanoutExchange");
        return "success";
    }
}

消费者:

package com.example.rabbitmq;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

@Component
public class Receiver {

    /**
     * @Exchange的type默认为ExchangeTypes.DIRECT,需要重写成ExchangeTypes.FANOUT
     * 这里不用写routingKey,写了不会报错,但它也不要
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "myQueue2"),
                    exchange = @Exchange(value = "myExchange2", type =ExchangeTypes.FANOUT)
            ))
    public void process2(Message message){
        System.out.println("myQueue2:" + new String(message.getBody()));
    }

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "myQueue3"),
                    exchange = @Exchange(value = "myExchange2", type =ExchangeTypes.FANOUT)
            ))
    public void process3(Message message) {
        System.out.println("myQueue3:" + new String(message.getBody()));
    }

 

启动项目,访问http://localhost:8080/helloRabbit2,控制台打印

myQueue3:fanoutExchange
myQueue2:fanoutExchange

你可能感兴趣的:(java,springboot,rabbitmq,后端,消息中间件)