RabbitMQ springboot Fanout广播订阅模式-消费者工程2

上接:RabbitMQ springboot创建父工程

创建消费者子模块

在父项目中,创建消费者子模块:fanout_sms

略

pom.xml

由于父项目已引入所有依赖包,所以pom.xml中不做任何修改

application.yml

server:
  port: 8002


spring:
  application:
    #服务名称
    name: rabbitmq-fanout-sms # 修改服务名
  #RabbitMQ的配置
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: guest
    password: guest

创建 RabbitMQ 监听器

生产者需要事先创建队列,然后才能发送消息,所以增加 配置类,启动时,自动创建 queue,这里是:sms

package top.malaoshi.rabbitmq;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class ConsumerListener {
    // 指定sms队列
    public static final String QUEUE_SMS="fanout_sms";
    public static final String EXCHANGE="fanout_exchange";
    //注册监听器,并指定消息队列名称
//    @RabbitListener(queues = NOTICE)
//    @RabbitListener(queuesToDeclare = @Queue(QUEUE_SMS))
    @RabbitListener(bindings = @QueueBinding(value = @Queue(QUEUE_SMS),exchange = @Exchange(value = EXCHANGE,type = ExchangeTypes.FANOUT)))
    public void receiveMsg(String msg, Channel channel, Message message){
        //msg:字符串消息
        System.out.println("收到消息:" + msg);
        System.out.println("channel通道编号为:" + channel.getChannelNumber());
        //可以通过Message对象,获取消息正文
        System.out.println("收到消息:" + new String(message.getBody()));
    }
}

自动创建队列、交换器,并进行绑定

@RabbitListener(bindings = @QueueBinding(value = @Queue(QUEUE_NOTICE),exchange = @Exchange(value = EXCHANGE,type = ExchangeTypes.FANOUT)))

这里必须指定 广播类型的交换器:type = ExchangeTypes.FANOUT,默认为 direct

事先创建队列

使用下面注解,需要事先创建好队列、和交换机,否则报错:

@RabbitListener(queues = QUEUE_SMS)

主启动类

package top.malaoshi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SMSMain {
    public static void main(String[] args) {
        SpringApplication.run(SMSMain.class, args);
    }
}

启动服务

启动主启动类

控制台会打印接收到的消息:

收到消息:李雷关注你
channel通道编号为:1
收到消息:李雷关注你

访问 rabbitmq web管理页面

此时创建 消息队列 sms 了