Springboot整合rabbitmq五种常用模型

本文档介绍了如何在Spring Boot项目中整合RabbitMQ,并通过配置文件设置连接信息。接着展示了五种消息模型的实现:HelloWorld模型、Work模型、Fanout广播模型、Route路由模式和Topic动态路由模式。每个模型都包含生产者和消费者的代码示例,详细解释了如何发送和接收消息。
摘要由CSDN通过智能技术生成

1.新建一个springboot项目
pom.xml如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cd</groupId>
    <artifactId>rabbitmq-springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>rabbitmq-springboot</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
                <!--rabbitmq与springboot整合依赖包-->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.编写application.yml配置文件

spring:
  application:
    name: rabbitmq-springboot
  rabbitmq:
    host: 192.168.57.136 # IP地址
    port: 5672          # 端口号
    username: ems       #用户名
    password: 123       # 密码
    virtual-host: /ems  # 虚拟主机名字

3.在springboot的测试类中编写如下五种模型
注意:当执行完上述步骤,springboot工程会自动创建一个RabbitmqTemplate对象来提供操作消息队列,我们只需要在使用的地方注入该类就行了
1.hello world模型

package com.cd.test;

import com.cd.RabbitmqSpringbootApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = RabbitmqSpringbootApplication.class)
@RunWith(SpringRunner.class)
public class TestRabbitmq {


    // 注入rabbitTemplate
    @Autowired
    private RabbitTemplate rabbitTemplate;


    // hello world 模型  该模型没有交换机
    @Test
    public void test(){
        // 向hello队列发送消息,不存在该队列就会创建 (在springboot中,必须要有消费者,不然只有生产者向队列中发消息而没有消费者,没啥意义,因此他就不会创建队列)
      rabbitTemplate.convertAndSend("hello","hello world");
    }

对应的消费者:

package com.cd.hello;

import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component    // 默认持久化  非独占  不是自动删除的队列
// 代表这是rabbitmq的一个消费者,监听hello这个队列,durable ="false"--是否持久化,autoDelete = "true---是否自动删除"
@RabbitListener(queuesToDeclare = @Queue(value = "hello",durable ="false",autoDelete = "true"))
public class HelloCustomer {


    @RabbitHandler  //代表从队列中取出消息时是通过如下回调方法去处理消息的
    public void receive1(String message){
        System.out.println("message"+message);
    }
}

2.work工作模型
对应生产者代码如下:

// work 模型   //该模型没有交换机
  @Test
  public void testWork(){
      for (int i = 0; i < 10; i++) {
           // 参数1:队列名称,参数2:消息
          rabbitTemplate.convertAndSend("work","work模型"+i);
      }

  }

消费者代码:

package com.cd.work;

import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class WorkConsumer {

    //一个消费者
    @RabbitListener(queuesToDeclare = @Queue("work"))
    public void receive1(String message){
        System.out.println("message1"+message);
    }

    //一个消费者
    @RabbitListener(queuesToDeclare = @Queue("work"))
    public void receive2(String message){
        System.out.println("message2"+message);
    }
}

3 fanout 广播模型
生产者代码:

//fanout  广播
    @Test
    public void testFanout(){
        // 参数1: 交换机名称,参数2:路由key(该模式下路由key没啥意义) 参数3:发送的消息内容
        rabbitTemplate.convertAndSend("logs","","Fanout模型发送的消息");
    }

消费者代码:

package com.cd.fanout;

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 FanoutCustomer {


    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue,  // 创建临时队列
                    exchange = @Exchange(value = "logs",type = "fanout") // 绑定的交换机
            )
    })
    public void receive1(String message){
        System.out.println("message"+message);
    }


    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue,  // 创建临时队列
                    exchange = @Exchange(value = "logs",type = "fanout") // 绑定的交换机
            )
    })
    public void receive2(String message){
        System.out.println("message"+message);
    }

}

4.//route 路由模式
生产者代码

//route  路由模式
    @Test
    public void testRoute(){
        // 参数1: 交换机名称,参数2:路由key 参数3:发送的消息内容
        rabbitTemplate.convertAndSend("directs","info","发送info的key的路由信息");
    }

消费者代码

package com.cd.route;

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 RouteCustomer {


     @RabbitListener(bindings = {
             @QueueBinding(
                     value = @Queue,  // 创建临时队列
                     exchange = @Exchange(name = "directs",type = "direct"), // 定义交换机的名称和类型
                     key = {"info","error","warn"} //匹配的路由
             )
     })
     public void receive1(String message){
         System.out.println("message1="+message);
     }

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue,  // 创建临时队列
                    exchange = @Exchange(name = "directs",type = "direct"), // 定义交换机的名称和类型
                    key = {"info","error","warn"}
            )
    })
    public void receive2(String message){
        System.out.println("message2="+message);
    }

}

5.topic 动态路由模式 // 动态路由模式

// 动态路由模式
    @Test
    public void testTopic(){
        // 参数1: 交换机名称,参数2:路由key 参数3:发送的消息内容
        rabbitTemplate.convertAndSend("topics","user.save","user.save 路由消息");
    }

消费者代码

package com.cd.topic;

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 TopicCustomer {
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue,  // 声明临时队列
                    exchange = @Exchange(name = "topics",type = "topic"),
                    key = {"user.save","user.*"}
            )
    })
    public void receive1(String message){
        System.out.println("message1="+message);
    }

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue,  // 声明临时队列
                    exchange = @Exchange(name = "topics",type = "topic"),
                    key = {"order.#","produce.#","user.*"}
            )
    })
    public void receive2(String message){
        System.out.println("message2="+message);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值