SpringBoot + RabbitMQ (一篇足以)

1,440 阅读4分钟

一、摘要
1.文章目录

·摘要
 -文章目录
 -项目结构
.开始使用
 -添加pom包
 -配置文件编辑
 -队列配置
 -发送者类编辑
 -接收者类编辑
 -测试类编辑
 -结果展示
·结果展示
 -自定义对象的发送与接收
 -Topic Exchange的使用
 -Fanout Exchange的使用
·文章推荐
 -一个源码解读
 -一个视频教程

2.项目结构
图中圈出的为关键类

二、开始使用
1.添加pom包,主要添加 1.添加pom包,主要添加 spring-boot-starter-amqp

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2.配置文件编辑,主要配置mq的地址、端口、用户名、密码以及路径

spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/

如下图:

3.队列配置(这个很关键,新手容易遗忘)

@Bean
public Queue Queue(){
    //参数中可包含队列的属性以及持久化等设置,交换机同理
    return new Queue("hello"); //这边使用默认交换机所以不需要进行声明以及绑定
}

备注:@Configuration并不是一个新的注解,在Spring3.0时已经存在了。@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。-- 新手怕忘 嘻嘻
4.发送者

    @Autowired
    private AmqpTemplate rabbitTemplate;

    //发送消息
    public Boolean SendMessage(String p_Message){
        try {
            Integer i = 0; //声明一个标志
            while (true){ //循环发送
                System.out.println("Sender : " + p_Message + i);
                this.rabbitTemplate.convertAndSend("hello", p_Message + i);//参数:routingKey,消息内容
                i++;
                Thread.sleep(5000);//5s发送一次
            }
        }
        catch (Exception ex){
            return  false;
        }
    }

5.接收者

//这边需要注意,这里面的【hello】 是你需要监听的队列的名称
@RabbitListener(queues = "hello")
@RabbitHandler
public void process(String p_Message) {
    System.out.println("Receiver  : " + p_Message);
}

备注:发送者的队列要和监听者的队列名一致,消息才能被正确接收
6.测试类

@Autowired
RabbitMqSendServices rabbitMqSendServices;
@Test
void sendMsg(){
	rabbitMqSendServices.SendMessage("hello");//参数:需要发送的内容
}

备注:这边需要知道的是,消息接收者类在项目启动的时候会被自动监听队列中的消息,无需另外写测试类进行启动,涉及到的关键注解是@RabbitListener(queues = "hello"),这里我刚开始学的时候看了网上的博客 都没有这个测试类很奇怪,也没说明,所以备注一下
7.运行结果

三、高级使用
1.自定义对象的发送与接收

//发送者
public Boolean SendMessage(String p_RoutingKey){
    try {
        Integer i = 0; //声明一个标志
        while (true){ //循环发送
            Department department = new Department();//声明对象
            department.setName("han");
            department.setId(i);
            System.out.println("Sender : " + department);
            this.rabbitTemplate.convertAndSend(p_RoutingKey,department);//参数:routingKey,消息内容
            Thread.sleep(5000);//5s发送一次
            i++;
        }
    }
    catch (Exception ex){
        return  false;
    }
}

//接收者
@RabbitListener(queues = "objectQueue")
public void obQueueProcess(Department p_Department) {
    System.out.println("Receiver  : " + p_Department.getName() + p_Department.getId());
}

//配置类中的定义
@Bean
public Queue ObQueue(){
    return new Queue("objectQueue");
}
@Bean
public MessageConverter messageConverter(){ //声明一个Json转化器,这个很关键
    return new Jackson2JsonMessageConverter();
}

//测试类
@Test
void sendObMsg(){
	rabbitMqSendServices.SendMessage("objectQueue");
}

//实体对象类
public class Department {
    private Integer id;
    private String name;

    public Integer getId(){
        return  id;
    }
    public String getName(){
        return name;
    }
    public void setId(Integer id){
        this.id = id;
    }
    public void setName(String name){
        this.name = name;
    }
}

2.Topic Exchange的使用
·配置文件定义

 //定义队列名称
final static String topicQueueOne = "topic.queueOne";
final static String topicQueueTwo = "topic.queueTwo";

@Bean
public Queue queueTopicQueueOne(){
    return new Queue(topicQueueOne);//参数:队列名称
}

@Bean
public Queue queueTopicQueueTwo(){
    return new Queue(topicQueueTwo);
}

@Bean
TopicExchange topicExchange(){
    return new TopicExchange("topicExchange_HanTest");//参数:交换机名称
}

//参数:队列,交换机,routingkey
@Bean
Binding bindingExchangeQueueOne(Queue queueTopicQueueOne, TopicExchange topicExchange){
    return BindingBuilder.bind(queueTopicQueueOne).to(topicExchange).with("topic.message");
}
@Bean
Binding bindingExchangeQueueTwo(Queue queueTopicQueueTwo, TopicExchange topicExchange){
    return BindingBuilder.bind(queueTopicQueueTwo).to(topicExchange).with("topic.#");
}

·发送者

//参数:交换机名称,routingkey,消息
public Boolean sendMessage(String p_ExchangeName,String p_RoutingKey,String p_Message){
    try {
        Integer i = 0; //声明一个标志
        while (true){ //循环发送
            String msg =  p_Message + i;
            System.out.println("Sender : " +msg);
            rabbitTemplate.convertAndSend(p_ExchangeName,p_RoutingKey,msg);
            i++;
            Thread.sleep(5000);//5s发送一次
        }
    }
    catch (Exception ex){
        return  false;
    }
}

·接收者

@RabbitListener(queues = "topic.queueOne")
public void queueOneProcess(String p_Message){
    System.out.println("Receiver  One : " + p_Message);
}
@RabbitListener(queues = "topic.queueTwo")
public void queueTwoprocess(String p_Message){
    System.out.println("Receiver  Two : " + p_Message);
}

·测试类

@Test
void sendTopicMsg1(){
	rabbitMqSendServices.sendMessage("topicExchange_HanTest","topic.message","salahei");
}
@Test
void sendTopicMsg2(){
	rabbitMqSendServices.sendMessage("topicExchange_HanTest","topic.other","salahei");
}

3.Fanout Exchange的使用
·配置文件定义

//声明队列
@Bean
public Queue fanoutQueueOne(){
    return new Queue("fanoutOne");
}
@Bean
public Queue fanoutQueueTwo(){
    return new Queue("fanoutTwo");
}
@Bean
public Queue fanoutQueueThree(){
    return new Queue("fanoutThree");
}

//声明交换机
@Bean
FanoutExchange fanoutExchange(){
    return new FanoutExchange("fanoutExchange_HanTest");
}

//绑定队列
@Bean
Binding bindingExchangeOne(Queue fanoutQueueOne,FanoutExchange fanoutExchange){
    return BindingBuilder.bind(fanoutQueueOne).to(fanoutExchange);
}
@Bean
Binding bindingExchangeTwo(Queue fanoutQueueTwo,FanoutExchange fanoutExchange){
    return BindingBuilder.bind(fanoutQueueTwo).to(fanoutExchange);
}
@Bean
Binding bindingExchangeThree(Queue fanoutQueueThree,FanoutExchange fanoutExchange){
    return BindingBuilder.bind(fanoutQueueThree).to(fanoutExchange);
}

·发送者

//参数:交换机名称,消息 -- //备注:fanout以及head类型的交换机是不要绑定routingkey的
public Boolean sendMessage(String p_ExchangeName,String p_Message){
    try {
        Integer i = 0; //声明一个标志
        while (true){ //循环发送
            String msg =  p_Message + i;
            System.out.println("Sender : " +msg);
            rabbitTemplate.convertAndSend(p_ExchangeName,"",msg);
            i++;
            Thread.sleep(5000);//5s发送一次
        }
    }
    catch (Exception ex){
        return  false;
    }
}

·接收者

@RabbitListener(queues = "fanoutOne")
public void fanoutProcessOne(String p_Message){
    System.out.println("Receiver  : " + p_Message);
}

//同时监听多个队列
@RabbitListener(queues = {"fanoutTwo","fanoutThree"})
public void fanoutProcessThree(String p_Message){
    System.out.println("Receiver  : " + p_Message);
}

·测试类

@Test
void sendFanoutMsg(){
	rabbitMqSendServices.sendMessage("fanoutExchange_HanTest","salahei");
}

@文章引用:
@RabbitListener实现过程的源码解读 -- 认为写的不错的一篇文章 from JinchaoLv SpringBoot视频教程 -- 一个详细易懂的学习视频 from 代码基基