RabbitMQ springboot Routing路由(Direct)订阅模式-消费者工程1

上接:RabbitMQ springboot创建父工程

创建消费者子模块

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

略

pom.xml

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

application.yml

server:
  port: 8001


spring:
  application:
    #服务名称
    name: rabbitmq-direct-notice
  #RabbitMQ的配置
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: guest
    password: guest

创建 RabbitMQ 监听器

消费者需要事先创建队列,然后才能接收消息,所以增加 配置类,启动时,自动创建 queue

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 {
    public static final String QUEUE_NOTICE="direct_notice";
    public static final String EXCHANGE="direct_exchange";
    public static final String KEY_NOTICE="key_notice";

    //注册监听器,并指定消息队列名称
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(QUEUE_NOTICE),
                    key = KEY_NOTICE,
                    exchange = @Exchange(
                            value = EXCHANGE,
                            type = ExchangeTypes.DIRECT)))
    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),
                    key = KEY_NOTICE,
                    exchange = @Exchange(
                            value = EXCHANGE,
                            type = ExchangeTypes.DIRECT)))
  • 指定队列名称
  • 指定交换器名称
  • 指定 key = KEY_NOTICE,即:RoutingKey
  • 可以不指定 交换器类型:type = ExchangeTypes.DIRECT,因为默认为 direct

主启动类

package org.malaoshi;

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

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

启动服务

启动主启动类

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

收到消息:abc
channel通道编号为:1
收到消息:abc

访问 rabbitmq web管理页面

此时创建 消息队列 direct_notice 了