栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

实战:SpringBoot整合RabbitMQ

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

实战:SpringBoot整合RabbitMQ

实战:SpringBoot整合RabbitMQ

RabbitMQ六种工作模式

上文介绍了RabbitMQ的六种工作模式,下面简单使用SpringBoot整合一下RabbitMQ,看看SpringBoot对RabbitMQ的封装是怎样的?

RabbitTemplate

RabbitTemplate:消息模板。

如同JdbcTemplate或者RedisTemplate一样,这是spring整合rabbit提供的消息模板。是进行发送消息的关键类。

功能:

该类提供了丰富的发送方法,包括可靠性投递消息方法、回调监听消息接口ConfirmCallback、返回值确认接口ReturnCallBack等等。同样我们需要注入到spring容器中,然后就可以想其他bean那样正常使用了。

生产者项目搭建 创建工程

创建一个工程SpringBoot-mq-producer,对应生产者:

添加相关依赖:

为了方便测试,我们也可以引入Thymeleaf的启动器:


    org.springframework.boot
    spring-boot-starter-thymeleaf

环境配置

通过查看SpringBoot中RabbitMQ对应的自动配置类 RabbitAutoConfiguration 可以看到,SpringBoot已经给RabbitMQ进行了默认的配置

配置的属性都对应在 RabbitProperties 中:

因此,我们可以在yaml中,对我们自己的环境进行配置,在两个工程中分别配置:

server:
  # web服务器端口号
  port: 8080
spring:
  #RabbitMQ配置
  rabbitmq:
    # 设置mq服务器连接地址
    host: 192.168.6.200
    # 设置用户名
    username: soberw
    # 设置密码
    password: 123456
    # 设置连接端口
    port: 5673
    # 设置虚拟主机名称
    virtual-host: /

接下来就 work queues工作队列模式 以及 topic主题模式 展开举例。

topic模式的搭建还是比较简单的,这里就先从topic开始:

Topic主题模式 配置类创建

此时还未创建交换机、队列等信息,因此我们还需要声明一个配置类RabbitMQConfig,

以对相关信息进行配置:

package com.soberw.springbootmqproducer.config;

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


@Configuration
public class RabbitMQConfig {

    
    public static final String TOPIC_EXCHANGE_NAME = "topic_exchange";
    
    public static final String TOPIC_QUEUE_NAME1 = "topic_queue1";
    public static final String TOPIC_QUEUE_NAME2 = "topic_queue2";

    
    @Bean("topicExchange")
    public Exchange topicExchange() {
        //第二个参数为是否支持持久化
        //对于不同的订阅模式,只需要调用不同的方法即可
        return ExchangeBuilder.topicExchange(TOPIC_EXCHANGE_NAME).durable(true).build();
    }

    
    @Bean("topicQueue1")
    public Queue topicQueue1() {
        return QueueBuilder.durable(TOPIC_QUEUE_NAME1).build();
    }

    
    @Bean("topicQueue2")
    public Queue topicQueue2() {
        return QueueBuilder.durable(TOPIC_QUEUE_NAME2).build();
    }

    
    @Bean
    public Binding topicQueueExchange1(@Qualifier("topicQueue1") Queue queue,
                                     @Qualifier("topicExchange") Exchange exchange) {
        //将哪个队列绑定到哪个交换机上,且对应的routingKey是什么
        return BindingBuilder.bind(queue).to(exchange).with("info.#").noargs();
    }
    @Bean
    public Binding topicQueueExchange2(@Qualifier("topicQueue2") Queue queue,
                                       @Qualifier("topicExchange") Exchange exchange) {
        //将哪个队列绑定到哪个交换机上,且对应的routingKey是什么
        return BindingBuilder.bind(queue).to(exchange).with("error.#").noargs();
    }

}

这里声明了两个匹配规则,对应着两个队列去接收:

  • info.#
  • error.#

这里我们调用的是对应topic的交换机创建方法,如果需要创建其他两种,只需要调用不同的方法即可:

模拟发送消息

简单的创建一个页面,模拟用户发送的消息,并创建一个Conroller控制类接收,存放在队列中:




    
    生产者



routingKey:
msg:

对应的Controller实现:

package com.soberw.springbootmqproducer.config.controller;

import com.soberw.springbootmqproducer.config.RabbitMQConfig;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/index")
public class IndexController {

    @Autowired(required = false)
    RabbitTemplate rabbitTemplate;

    @PostMapping("/testTopic")
    public String testSimple(@RequestParam("routingKey") String routingKey, @RequestParam("msg") String msg) {
        
        rabbitTemplate.convertAndSend(RabbitMQConfig.TOPIC_EXCHANGE_NAME, routingKey, msg);
        //返回消息
        return "发送消息成功!";
    }

}

产生了两个匹配不同规则的队列:

现在前台发送消息:

成功接收到:

队列中存在了此消息

再发送匹配error.#的:

Work Queues 工作队列模式

前面我们知道,此种模式有两种竞争处理:

  • 公平竞争
  • 不公平竞争

公平竞争比较好实现,这里不再演示,这里主要举例如何实现不公平分发,即在SpringBoot中如何实现手动确认以及预先抓取。

添加配置项

同样需要在配置类中创建队列,而因为是工作模式,不需要创建交换机,继续沿用上面的配置类,添加新的配置项:

public static final String WORK_QUEUE_NAME = "work_queue";

@Bean("workQueue")
public Queue workQueue() {
    return QueueBuilder.durable(WORK_QUEUE_NAME).build();
}
模拟发送消息

添加发送work消息的表单:


消息内容:

对应的控制层方法:

@PostMapping("/testWork")
public String testWork(@RequestParam("msg") String msg) {
    if (msg == null || "".equals(msg)) {
        return "请输入正确的信息!";
    }
    for (int i = 0; i < 10; i++) {
        rabbitTemplate.convertAndSend(RabbitMQConfig.WORK_QUEUE_NAME, msg);
    }
    return "消息发送成功!";
}

测试一下:

去往控制面板查看:

消费者项目搭建 创建工程

与生产者同样的创建步骤:

环境配置

因为在work模式中需要手动确认消息,因此需要在配置文件中进行配置:

spring:
  #RabbitMQ配置
  rabbitmq:
    # 设置mq服务器连接地址
    host: 192.168.6.200
    # 设置用户名
    username: soberw
    # 设置密码
    password: 123456
    # 设置连接端口
    port: 5672
    # 设置虚拟主机名称
    virtual-host: /
    listener:
      simple:
        # 设置消息的确认方式,设置为手动确认
        acknowledge-mode: MANUAL
        prefetch: 1
Topic主题模式 队列监听器

消息如何从队列中拿到呢?

只需要创建一个队列监听器,绑定上将要监听的队列即可,监听器会自动从队列中获取消息,当然也可以选择实现RabbitMQ提供的监听器接口方式去实现,这里不再演示(注意不要导错包):

如果使用的是注解的方式,则只需要在方法上添加@RabbitListener注解,并指定将要绑定的队列名称即可绑定,在方法入参中,写入想要获取的值,如同SpringMVC的处理方式一样,会自动返回给你,例如信道Channel、消息Message、或者只获取发送的消息体msg。

package com.soberw.springbootmqconsumer.listener;

import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


@Component
public class TopicListener {


    
    @SneakyThrows
    @RabbitListener(queues = "topic_queue1")
    public void queue1(Message message, Channel channel) {
        byte[] body = message.getBody();
        System.out.println("msg = " + new String(body));
        //手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    
    @RabbitListener(queues = "topic_queue2")
    @SneakyThrows
    public void queue2(Message message,Channel channel) {
        byte[] body = message.getBody();
        System.out.println("msg = " + new String(body));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
模拟接收消息

将两个项目同时启动,观察消费者控制台,打印信息:

可以看到,刚才发送的消息已经被取出来了。

队列中的也已经被取出来了。

下面生产者发送一条:

对应的队列也成功监听到消息。

Work Queues 工作队列模式 队列监听器
package com.soberw.springbootmqconsumer.listener;

import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


@Component
public class WorkListener {

    
    @SneakyThrows
    @RabbitListener(queues = "work_queue")
    public void workQueue1(Channel channel, Message message) {
        TimeUnit.SECONDS.sleep(1);
        channel.basicQos(1);
        System.out.println("body1: " + new String(message.getBody()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    @SneakyThrows
    @RabbitListener(queues = "work_queue")
    public void workQueue2(Channel channel, Message message) {
        TimeUnit.SECONDS.sleep(2);
        channel.basicQos(1);
        System.out.println("body2: " + new String(message.getBody()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
模拟接收消息

生产者发送消息:

因此实现了不公平分发。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/946404.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号