超详细RabbitMq入门教程

RabbitMq入门教程

准备工作:安装rabbit参照

https://blog.csdn.net/jiayou516/article/details/119183297?spm=1001.2014.3001.5501

一.RabbitMQ-SpringBoot案例 -fanout模式

在这里插入图片描述

在这里插入图片描述

实现步骤

1:创建生产者工程:sspringboot-rabbitmq-fanout-producer
2:创建消费者工程:springboot-rabbitmq-fanout-consumer
3:引入spring-boot-rabbitmq的依赖
4:进行消息的分发和测试
5:查看和观察web控制台的状况

具体实现

定义生产者
1:创建生产者工程:springboot-rabbitmq-fanout-producer

在这里插入图片描述

2:在pom.xml中引入依赖
<dependency>
    <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>
3:在application.yml进行配置
# 服务端口
server:
  port: 10086
# 配置rabbitmq服务
spring:
  rabbitmq:
    username: admin
    password: admin
    virtual-host: /root
    host: localhost
    port: 5672
4:定义订单的生产者
package com.demo.fanout.service;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @className: OrderService
 * @description: 订单
 * @author: penghailan
 * @create: 2021-07-26 10:14
 **/
@Component
public class OrderService {
   
    @Autowired
    private RabbitTemplate rabbitTemplate;
    //定义交换机
    private String exchangeName = "fanout_order_exchange";
    //路由key
    private String routeKey = "";
    public void saveOrder(Long userId,Long productId,int num){
   
        //1.生成订单号
        String orderNumber = UUID.randomUUID().toString();
        //2.根据商品id productId查询商品库存
        // int numstore = productSerivce.getProductNum(productId);
        // 3:判断库存是否充足
        // if(num >  numstore ){ return  "商品库存不足..."; }
        // 4: 下单逻辑
        // orderService.saveOrder(order);
        // 5: 下单成功要扣减库存
        // 6: 下单完成以后
        System.out.println("用户:"+userId+",订单编号是:"+orderNumber);
        //发送订单信息给rabbitMQ fanout
        rabbitTemplate.convertAndSend(exchangeName,routeKey,orderNumber);
    }
}

5:绑定关系
package com.demo.fanout.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @className: DirectRabbitConfig
 * @description: 配置类
 * @author: penghailan
 * @create: 2021-07-26 10:23
 **/
@Configuration
public class DirectRabbitConfig {
   
    //声明email队列
    @Bean
    public Queue emailQueue(){
   
        // durable:是否持久化,默认是false,持久化队列:会被存储在磁盘上,当消息代理重启时仍然存在,暂存队列:当前连接有效
        // exclusive:默认也是false,只能被当前创建的连接使用,而且当连接关闭后队列即被删除。此参考优先级高于durable
        // autoDelete:是否自动删除,当没有生产者或者消费者使用此队列,该队列会自动删除。
        //一般设置一下队列的持久化就好,其余两个就是默认false
        return new Queue("email.fanout.queue",true);
    }
    //声明sms队列
    @Bean
    public Queue smsQueue(){
   
        return new Queue("sms.fanout.queue",true);
    }
    //声明微信队列
    @Bean
    public Queue weixinQueue(){
   
        return new Queue("weixin.fanout.queue",true);
    }
    //声明交换机
    @Bean
    public FanoutExchange fanoutOrderExchange(){
   
        return new FanoutExchange("fanout_order_exchange",true,false);
    }
    //将队列和交换机进行绑定
    @Bean
   public Binding bingingFanout1(){
   
       return BindingBuilder.bind(emailQueue()).to(fanoutOrderExchange());
   }

    @Bean
    public Binding bingingFanout2(){
   
        return BindingBuilder.bind(smsQueue()).to(fanoutOrderExchange());
    }
    @Bean
    public Binding bingingFanout3(){
   
        return BindingBuilder.bind(weixinQueue()).to(fanoutOrderExchange());
    }

}

6.编写测试
package com.demo.fanout;

import com.demo.fanout.service.OrderService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbootRabbitmqFanoutProducerApplicationTests {
   

    @Autowired
    private OrderService orderService;

    @Test
    void contextLoads() throws InterruptedException {
   
        for (int i = 0; i < 10; i++) {
   
            Thread.sleep(1000);
            Long userId = 1000L + i;
            Long productId = 1000L + i;
            int num = 10;
            orderService.saveOrder(userId,productId,num);
        }
    }

}

控制台输出

在这里插入图片描述

管理界面

在这里插入图片描述

定义消费者
1、创建消费者工程:springboot-rabbitmq-fanout-consumer

在这里插入图片描述

2、引入依赖pom.xml
<dependency>
    <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>
3、在application.yml进行配置
# 服务端口
server:
  port: 10088
# 配置rabbitmq服务
spring:
  rabbitmq:
    username: admin
    password: admin
    virtual-host: /root
    host: localhost
    port: 5672

4、消费者 - 邮件服务
package com.demo.fanout.consumer;

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

/**
 * @className: EmailService
 * @description: email服务
 * @author: penghailan
 * @create: 2021-07-26 11:22
 **/
@Component
@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "email.fanout.queue"),
                                exchange = @Exchange(value = "fanout_order_exchange",type = ExchangeTypes.FANOUT)))
public class EmailService {
   
    @RabbitHandler
    public void emailService(String message){
   
        //具体的发邮件业务逻辑代码
        System.out.println("email-------------->" + message);
    }
}

5、消费者 - 短信服务
package com.demo.fanout.consumer;

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

/**
 * @className: SMSService
 * @description: 短信服务
 * @author: penghailan
 * @create: 2021-07-26 11:07
 **/
@Component
@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "sms.fanout.queue"),
                                        exchange = @Exchange(value = "fanout_order_exchange",type = ExchangeTypes.FANOUT)))
public class SMSService {
   
    @RabbitHandler
    public void messageService(String message){
   
        //发短信的逻辑
        System.out.println("sms---------->"+message);
    }

}

6、消费者 - 微信服务
package com.demo.fanout.consumer;

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

/**
 * @className: WeixinService
 * @description: 微信服务
 * @author: penghailan
 * @create: 2021-07-26 11:15
 **/
@Component
@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "weixin.fanout.queue",durable = "true"),
                                        exchange = @Exchange(value = "fanout_order_exchange",type = ExchangeTypes.FANOUT)))
public class WeixinService {
   
    @RabbitHandler
    public void messageService(String message){
   
        //省略微信发邮件的具体业务代码
        System.out.println("weixin-------------->" + message);
    }
}

7、启动服务SpringbootRabbitmqFanoutConsumerApplication,查看效果

在这里插入图片描述

二.RabbitMQ-SpringBoot案例 -direct模式

Direct模式是fanout模式上的一种叠加,增加了路由RoutingKey的模式。

在这里插入图片描述

实现步骤

1:创建生产者工程:sspringboot-rabbitmq-direct-producer
2:创建消费者工程:springboot-rabbitmq-direct-consumer
3:引入spring-boot-rabbitmq的依赖
4:进行消息的分发和测试
5:查看和观察web控制台的状况

具体实现

定义生成者
1、创建生产者工程:springboot-rabbitmq-direct-producer

在这里插入图片描述

2、在pom.xml中引入依赖
<dependency>
    <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>
3、在application.yml进行配置
# 服务端口
server:
  port: 10096
# 配置rabbitmq服务
spring:
  rabbitmq:
    username: admin
    password: admin
    virtual-host: /root
    host: localhost
    port: 5672

4、定义订单的生产者
package com.demo.direct.service;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @className: OrderService
 * @description: 订单服务
 * @author: penghailan
 * @create: 2021-07-26 13:54
 **/
@Component
public class OrderService {
   
    @Autowired
    private RabbitTemplate rabbitTemplate;
    //定义交换机
    private String exchangeName = "dire_order_exchange";
    private String routeKey="";
    private String routeKey1="sms";
    private String routeKey2="email";
    private String routeKey3="weixin";

    public void saveOrder(Long userId,Long productId,int num){
   
        // 1: 模拟用户下单
        String orderNumer = UUID.randomUUID().toString();
        // 2: 根据商品id productId 去查询商品的库存
        // int numstore = productSerivce.getProductNum(productId);
        // 3:判断库存是否充足
        // if(num >  numstore ){ return  "商品库存不足..."; }
        // 4: 下单逻辑
        // orderService.saveOrder(order);
        // 5: 下单成功要扣减库存
        // 6: 下单完成以后
        System.out.println("用户 " + userId + ",订单编号是:" + orderNumer);
        // 发送订单信息给RabbitMQ fanout
       // rabbitTemplate.convertAndSend(exchangeName, routeKey, orderNumer);//不指定routeKey,则三个队列都会收到消息
        rabbitTemplate.convertAndSend(exchangeName, routeKey1, orderNumer);//指定routeKey,给指定的队列发消息
        rabbitTemplate.convertAndSend(exchangeName, routeKey2, orderNumer);
        rabbitTemplate.convertAndSend(exchangeName, routeKey3, orderNumer);
    }
}

5、绑定关系
package com.demo.direct.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @className: DirectRabbitConfig
 * @description: 配置类
 * @author: penghailan
 * @create: 2021-07-26 13:58
 **/
@Configuration
public class DirectRabbitConfig {
   

    //声明队列
    @Bean
    public Queue emailQueue(){
   
        return new Queue("email.dire.queue",true);
    }
    //声明队列
    @Bean
    public Queue smsQueue(){
   
        return new Queue("sms.dire.queue",true);
    }
    //声明队列
    @Bean
    public Queue weixinQueue(){
   
        return new Queue("weixin.dire.queue",true);
    }
    //声明交换机
    @Bean
    public DirectExchange direExchange(){
   
        return new DirectExchange("dire_order_exchange",true,false);
    }
    //将队列与交换机进行绑定,并设置用于匹配的routeKey
    @Bean
    public Binding bindingDirect1(){
   
        return BindingBuilder.bind(emailQueue()).to(direExchange()).with("");
    }
    @Bean
    public Binding bindingDirect3(){
   
        return BindingBuilder.bind(smsQueue()).to(direExchange()).with("");
    }
    @Bean
    public Binding bindingDirect2(){
   
        return BindingBuilder.bind(weixinQueue()).to(direExchange()).with("");
    }

}

6、进行测试
package com.demo.fanout;

import com.demo.fanout.service.OrderService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbootRabbitmqFanoutProducerApplicationTests {
   

    @Autowired
    private OrderService orderService;

    @Test
    void contextLoads() throws InterruptedException {
   
        for (int i = 0; i < 10; i++) {
   
            Thread.sleep(1000);
            Long userId = 1000L + i;
            Long productId = 1000L + i;
            int num = 10;
            orderService.saveOrder(userId,productId,num);
        }
    }

}

在这里插入图片描述

定义消费者
1、创建生产者工程:springboot-rabbitmq-direct-consumer

在这里插入图片描述

2、在pom.xml中引入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</
  • 20
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
RabbitMQ 是一个开源的消息队列系统,它可以用于在应用程序之间传递消息。下面是一个简单的 RabbitMQ 中文教程: 1. 安装 RabbitMQ:你可以从 RabbitMQ 的官方网站下载适合你操作系统的安装包,并按照官方文档的说明进行安装。 2. 启动 RabbitMQ 服务器:安装完成后,你可以启动 RabbitMQ 服务器。在大多数情况下,它会自动启动并运行在默认端口上(5672)。 3. 创建连接:使用你的编程语言(如 Python、Java、JavaScript等)连接到 RabbitMQ 服务器。你需要提供服务器的地址、端口、用户名和密码等信息来建立连接。 4. 创建队列:使用 RabbitMQ 的管理界面或编程语言的客户端库来创建一个队列队列用于存储消息,应用程序可以通过队列收发消息。 5. 发布消息:使用编程语言的客户端库将消息发布到队列中。你可以指定消息的内容和其他属性。 6. 消费消息:使用编程语言的客户端库从队列消费消息。你可以注册一个消费者来处理从队列中获取到的消息。 7. 确认消息:在消费消息后,你可以发送确认给 RabbitMQ,表示消息已被处理。RabbitMQ 将从队列中删除已确认的消息。 8. 关闭连接:当你完成所有操作后,记得关闭与 RabbitMQ 的连接。 这只是一个简单的 RabbitMQ 中文教程,你可以根据需要深入学习 RabbitMQ 的更多特性和用法。文档和官方网站上有更详细的教程和示例代码可供参考。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值