手把手带你 SpringBoot 2.X 整合 rocketmq-spring-boot-starter 2.2.0

我的springboot的版本是2.1.3 rocketmq-spring-boot-starter版本是2.2.0

1 安装RocketMq并启动

参考我之前的文章 Windows环境下单机安装RocketMQ

2 开始整合

先看一下大概的目录
在这里插入图片描述

  • 2.1 引入maven库
      <dependency>
            <groupId>org.apache.rocketmq</groupId>
            <artifactId>rocketmq-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>
  • 2.2配置文件
server:
  port: 8088
#rocketmq配置
rocketmq:
  name-server: 127.0.0.1:9876
  # 生产者配置
  producer:
    isOnOff: on
    # 发送同一类消息的设置为同一个group,保证唯一
    group: user-rocketmq-group
    groupName: user-rocketmq-group

    group1: order-rocketmq-group
    groupName1: order-rocketmq-group
    # 服务地址
    namesrvAddr: 127.0.0.1:9876
    # 消息最大长度 默认1024*4(4M)
    maxMessageSize: 4096
    # 发送消息超时时间,默认3000
    sendMsgTimeout: 3000
    # 发送消息失败重试次数,默认2
    retryTimesWhenSendFailed: 2
  • 2.3 RocketMqHelper 工具类
package com.example.utils;

/**
 * @author guog
 * @create 2021-04-21 17:38
 */

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * RocketMq助手
 *
 * @Author: heyuhua
 * @Date: 2020/1/8 10:03
 */
@Component
public class RocketMqHelper {

    /**
     * 日志
     */
    private static final Logger LOG = LoggerFactory.getLogger(RocketMqHelper.class);

    /**
     * rocketmq模板注入
     */
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @PostConstruct
    public void init() {
        LOG.info("---RocketMq助手初始化---");
    }

    /**
     * 发送异步消息
     *
     * @param topic   消息Topic
     * @param message 消息实体
     */
    public void asyncSend(Enum topic, Message<?> message) {
        asyncSend(topic.name(), message, getDefaultSendCallBack());
    }


    /**
     * 发送异步消息
     *
     * @param topic        消息Topic
     * @param message      消息实体
     * @param sendCallback 回调函数
     */
    public void asyncSend(Enum topic, Message<?> message, SendCallback sendCallback) {
        asyncSend(topic.name(), message, sendCallback);
    }

    /**
     * 发送异步消息
     *
     * @param topic   消息Topic
     * @param message 消息实体
     */
    public void asyncSend(String topic, Message<?> message) {
        rocketMQTemplate.asyncSend(topic, message, getDefaultSendCallBack());
    }

    /**
     * 发送异步消息
     *
     * @param topic        消息Topic
     * @param message      消息实体
     * @param sendCallback 回调函数
     */
    public void asyncSend(String topic, Message<?> message, SendCallback sendCallback) {
        rocketMQTemplate.asyncSend(topic, message, sendCallback);
    }

    /**
     * 发送异步消息
     *
     * @param topic        消息Topic
     * @param message      消息实体
     * @param sendCallback 回调函数
     * @param timeout      超时时间
     */
    public void asyncSend(String topic, Message<?> message, SendCallback sendCallback, long timeout) {
        rocketMQTemplate.asyncSend(topic, message, sendCallback, timeout);
    }

    /**
     * 发送异步消息
     *
     * @param topic        消息Topic
     * @param message      消息实体
     * @param sendCallback 回调函数
     * @param timeout      超时时间
     * @param delayLevel   延迟消息的级别
     */
    public void asyncSend(String topic, Message<?> message, SendCallback sendCallback, long timeout, int delayLevel) {
        rocketMQTemplate.asyncSend(topic, message, sendCallback, timeout, delayLevel);
    }

    /**
     * 发送顺序消息
     *
     * @param message
     * @param topic
     * @param hashKey
     */
    public void syncSendOrderly(Enum topic, Message<?> message, String hashKey) {
        syncSendOrderly(topic.name(), message, hashKey);
    }


    /**
     * 发送顺序消息
     *
     * @param message
     * @param topic
     * @param hashKey
     */
    public void syncSendOrderly(String topic, Message<?> message, String hashKey) {
        LOG.info("发送顺序消息,topic:" + topic + ",hashKey:" + hashKey);
        rocketMQTemplate.syncSendOrderly(topic, message, hashKey);
    }

    /**
     * 发送顺序消息
     *
     * @param message
     * @param topic
     * @param hashKey
     * @param timeout
     */
    public void syncSendOrderly(String topic, Message<?> message, String hashKey, long timeout) {
        LOG.info("发送顺序消息,topic:" + topic + ",hashKey:" + hashKey + ",timeout:" + timeout);
        rocketMQTemplate.syncSendOrderly(topic, message, hashKey, timeout);
    }

    /**
     * 默认CallBack函数
     *
     * @return
     */
    private SendCallback getDefaultSendCallBack() {
        return new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                LOG.info("---发送MQ成功---");
            }

            @Override
            public void onException(Throwable throwable) {
                LOG.error("---发送MQ失败---"+throwable.getMessage(), throwable.getMessage());
            }
        };
    }


    @PreDestroy
    public void destroy() {
        LOG.info("---RocketMq助手注销---");
    }

}
  • 2.4 创建User 和 Order 实体
package com.example.entity;

/**
 * @author guog
 * @create 2021-04-21 17:39
 */
public class User {
    String name;
    Integer id;
    Integer age;
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

package com.example.entity;

/**
 * @author guog
 * @create 2021-04-22 11:32
 */
public class Order {
    Integer id;
    String OrderType;
    String OrderNO;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getOrderType() {
        return OrderType;
    }

    public void setOrderType(String orderType) {
        OrderType = orderType;
    }

    public String getOrderNO() {
        return OrderNO;
    }

    public void setOrderNO(String orderNO) {
        OrderNO = orderNO;
    }
}
  • 2.5 创建消息监听
  • 2.5.1 UserMqListener
package com.example.Listener;

import com.example.entity.User;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

/**
 * @author guog
 * @create 2021-04-21 17:40
 */
@Component
@RocketMQMessageListener(consumerGroup = "${rocketmq.producer.groupName}", topic = "USER_ADD")
public class UserMqListener implements RocketMQListener<User> {
@Override
public void onMessage(User user) {
        System.out.println("----------------------------------");
        System.out.println("接收到消息,开始消费..name:" + user.getName() + ",age:" + user.getAge());
        }
        }
  • 2.5.2 OrderMqListener
package com.example.Listener;

import com.example.entity.Order;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

/**
 * @author guog
 * @create 2021-04-21 17:40
 */
@Component
@RocketMQMessageListener(consumerGroup = "${rocketmq.producer.groupName1}", topic = "ORDER_ADD",consumeMode = ConsumeMode.ORDERLY)
public class OrderMqListener implements RocketMQListener<Order> {
@Override
public void onMessage(Order order) {
                System.out.println("接收到消息,开始消费..OrderType:" + order.getOrderType() + ",OrderNO:" + order.getOrderNO());
        }
 }
  • 2.6 写一个testController测试代码
  • 2.6.1 测试异步发送并消费
  //发送异步消息
    @GetMapping("asyncSend")
    public void asyncSend() {
        User user= new User();
        user.setName("java");
        user.setAge(18);
        rocketMqHelper.asyncSend("USER_ADD", MessageBuilder.withPayload(user).build());
    }

查看结果
在这里插入图片描述

  • 2.6.1 测试顺序发送并消费
//发送顺序消息
    @GetMapping("syncSendOrderly")
    public void syncSendOrderly() {
        Order order1 = new Order();
        Order order2 = new Order();
        Order order3 = new Order();
        Order order4 = new Order();
        order1.setOrderNO("1111111");
        order2.setOrderNO("2222222");
        order3.setOrderNO("3333333");
        order4.setOrderNO("4444444");


        order1.setOrderType("创建订单");
        rocketMqHelper.syncSendOrderly("ORDER_ADD", MessageBuilder.withPayload(order1).build(),order1.getOrderNO());

        order2.setOrderType("创建订单");
        rocketMqHelper.syncSendOrderly("ORDER_ADD", MessageBuilder.withPayload(order2).build(),order2.getOrderNO());

        order2.setOrderType("支付订单");
        rocketMqHelper.syncSendOrderly("ORDER_ADD", MessageBuilder.withPayload(order2).build(),order2.getOrderNO());

        order3.setOrderType("创建订单");
        rocketMqHelper.syncSendOrderly("ORDER_ADD", MessageBuilder.withPayload(order3).build(),order3.getOrderNO());


        order1.setOrderType("支付订单");
        rocketMqHelper.syncSendOrderly("ORDER_ADD", MessageBuilder.withPayload(order1).build(),order1.getOrderNO());

        order2.setOrderType("已发货");
        rocketMqHelper.syncSendOrderly("ORDER_ADD", MessageBuilder.withPayload(order2).build(),order2.getOrderNO());


        order3.setOrderType("支付订单");
        rocketMqHelper.syncSendOrderly("ORDER_ADD", MessageBuilder.withPayload(order3).build(),order3.getOrderNO());

        order2.setOrderType("已收货");
        rocketMqHelper.syncSendOrderly("ORDER_ADD", MessageBuilder.withPayload(order2).build(),order2.getOrderNO());


        order1.setOrderType("已发货");
        rocketMqHelper.syncSendOrderly("ORDER_ADD", MessageBuilder.withPayload(order1).build(),order1.getOrderNO());



        order4.setOrderType("创建订单");
        rocketMqHelper.syncSendOrderly("ORDER_ADD", MessageBuilder.withPayload(order4).build(),order4.getOrderNO());

        order3.setOrderType("已发货");
        rocketMqHelper.syncSendOrderly("ORDER_ADD", MessageBuilder.withPayload(order3).build(),order3.getOrderNO());

        order4.setOrderType("支付订单");
        rocketMqHelper.syncSendOrderly("ORDER_ADD", MessageBuilder.withPayload(order4).build(),order4.getOrderNO());

        order1.setOrderType("已收货");
        rocketMqHelper.syncSendOrderly("ORDER_ADD", MessageBuilder.withPayload(order1).build(),order1.getOrderNO());


        order4.setOrderType("已发货");
        rocketMqHelper.syncSendOrderly("ORDER_ADD", MessageBuilder.withPayload(order4).build(),order4.getOrderNO());


        order3.setOrderType("已收货");
        rocketMqHelper.syncSendOrderly("ORDER_ADD", MessageBuilder.withPayload(order3).build(),order3.getOrderNO());

        order4.setOrderType("已收货");
        rocketMqHelper.syncSendOrderly("ORDER_ADD", MessageBuilder.withPayload(order4).build(),order4.getOrderNO());


    }

创建 4个Order对象 分别有4中状态 创建订单—》支付订单—》已发货----》已收货 我们测试看同一个订单号是否是按照这个顺序进行消费的

结果

2021-04-22 15:38:51.783  INFO 6632 --- [nio-8088-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 3 ms
2021-04-22 15:38:51.800  INFO 6632 --- [nio-8088-exec-1] com.example.utils.RocketMqHelper         : 发送顺序消息,topic:ORDER_ADD,hashKey:1111111
2021-04-22 15:38:51.967  INFO 6632 --- [nio-8088-exec-1] com.example.utils.RocketMqHelper         : 发送顺序消息,topic:ORDER_ADD,hashKey:2222222
2021-04-22 15:38:51.969  INFO 6632 --- [nio-8088-exec-1] com.example.utils.RocketMqHelper         : 发送顺序消息,topic:ORDER_ADD,hashKey:2222222
2021-04-22 15:38:51.970  INFO 6632 --- [nio-8088-exec-1] com.example.utils.RocketMqHelper         : 发送顺序消息,topic:ORDER_ADD,hashKey:3333333
2021-04-22 15:38:51.971  INFO 6632 --- [nio-8088-exec-1] com.example.utils.RocketMqHelper         : 发送顺序消息,topic:ORDER_ADD,hashKey:1111111
2021-04-22 15:38:51.972  INFO 6632 --- [nio-8088-exec-1] com.example.utils.RocketMqHelper         : 发送顺序消息,topic:ORDER_ADD,hashKey:2222222
2021-04-22 15:38:51.974  INFO 6632 --- [nio-8088-exec-1] com.example.utils.RocketMqHelper         : 发送顺序消息,topic:ORDER_ADD,hashKey:3333333
2021-04-22 15:38:51.975  INFO 6632 --- [nio-8088-exec-1] com.example.utils.RocketMqHelper         : 发送顺序消息,topic:ORDER_ADD,hashKey:2222222
2021-04-22 15:38:51.976  INFO 6632 --- [nio-8088-exec-1] com.example.utils.RocketMqHelper         : 发送顺序消息,topic:ORDER_ADD,hashKey:1111111
2021-04-22 15:38:51.976  INFO 6632 --- [nio-8088-exec-1] com.example.utils.RocketMqHelper         : 发送顺序消息,topic:ORDER_ADD,hashKey:4444444
2021-04-22 15:38:51.977  INFO 6632 --- [nio-8088-exec-1] com.example.utils.RocketMqHelper         : 发送顺序消息,topic:ORDER_ADD,hashKey:3333333
2021-04-22 15:38:51.978  INFO 6632 --- [nio-8088-exec-1] com.example.utils.RocketMqHelper         : 发送顺序消息,topic:ORDER_ADD,hashKey:4444444
2021-04-22 15:38:51.979  INFO 6632 --- [nio-8088-exec-1] com.example.utils.RocketMqHelper         : 发送顺序消息,topic:ORDER_ADD,hashKey:1111111
2021-04-22 15:38:51.980  INFO 6632 --- [nio-8088-exec-1] com.example.utils.RocketMqHelper         : 发送顺序消息,topic:ORDER_ADD,hashKey:4444444
2021-04-22 15:38:51.981  INFO 6632 --- [nio-8088-exec-1] com.example.utils.RocketMqHelper         : 发送顺序消息,topic:ORDER_ADD,hashKey:3333333
2021-04-22 15:38:51.982  INFO 6632 --- [nio-8088-exec-1] com.example.utils.RocketMqHelper         : 发送顺序消息,topic:ORDER_ADD,hashKey:4444444
接收到消息,开始消费..OrderType:创建订单,OrderNO:1111111
接收到消息,开始消费..OrderType:创建订单,OrderNO:4444444
接收到消息,开始消费..OrderType:创建订单,OrderNO:2222222
2021-04-22 15:39:49.312  INFO 6632 --- [MessageThread_2] a.r.s.s.DefaultRocketMQListenerContainer : consume C0A8640919E818B4AAC26F811A770000 cost: 31 ms
2021-04-22 15:39:49.312  INFO 6632 --- [MessageThread_1] a.r.s.s.DefaultRocketMQListenerContainer : consume C0A8640919E818B4AAC26F811AC90012 cost: 31 ms
2021-04-22 15:39:49.312  INFO 6632 --- [MessageThread_3] a.r.s.s.DefaultRocketMQListenerContainer : consume C0A8640919E818B4AAC26F811ABF0002 cost: 31 ms
接收到消息,开始消费..OrderType:支付订单,OrderNO:4444444
接收到消息,开始消费..OrderType:支付订单,OrderNO:2222222
接收到消息,开始消费..OrderType:创建订单,OrderNO:3333333
2021-04-22 15:39:49.314  INFO 6632 --- [MessageThread_1] a.r.s.s.DefaultRocketMQListenerContainer : consume C0A8640919E818B4AAC26F811ACA0016 cost: 0 ms
2021-04-22 15:39:49.314  INFO 6632 --- [MessageThread_2] a.r.s.s.DefaultRocketMQListenerContainer : consume C0A8640919E818B4AAC26F811AC20006 cost: 0 ms
2021-04-22 15:39:49.314  INFO 6632 --- [MessageThread_3] a.r.s.s.DefaultRocketMQListenerContainer : consume C0A8640919E818B4AAC26F811AC10004 cost: 0 ms
接收到消息,开始消费..OrderType:已发货,OrderNO:4444444
接收到消息,开始消费..OrderType:支付订单,OrderNO:1111111
2021-04-22 15:39:49.314  INFO 6632 --- [MessageThread_1] a.r.s.s.DefaultRocketMQListenerContainer : consume C0A8640919E818B4AAC26F811ACC001A cost: 0 ms
2021-04-22 15:39:49.314  INFO 6632 --- [MessageThread_2] a.r.s.s.DefaultRocketMQListenerContainer : consume C0A8640919E818B4AAC26F811AC40008 cost: 0 ms
接收到消息,开始消费..OrderType:已发货,OrderNO:2222222
2021-04-22 15:39:49.314  INFO 6632 --- [MessageThread_3] a.r.s.s.DefaultRocketMQListenerContainer : consume C0A8640919E818B4AAC26F811AC5000A cost: 0 ms
接收到消息,开始消费..OrderType:已收货,OrderNO:4444444
接收到消息,开始消费..OrderType:支付订单,OrderNO:3333333
2021-04-22 15:39:49.314  INFO 6632 --- [MessageThread_1] a.r.s.s.DefaultRocketMQListenerContainer : consume C0A8640919E818B4AAC26F811ACE001E cost: 0 ms
2021-04-22 15:39:49.314  INFO 6632 --- [MessageThread_2] a.r.s.s.DefaultRocketMQListenerContainer : consume C0A8640919E818B4AAC26F811AC6000C cost: 0 ms
接收到消息,开始消费..OrderType:已收货,OrderNO:2222222
2021-04-22 15:39:49.315  INFO 6632 --- [MessageThread_3] a.r.s.s.DefaultRocketMQListenerContainer : consume C0A8640919E818B4AAC26F811AC7000E cost: 1 ms
接收到消息,开始消费..OrderType:已发货,OrderNO:1111111
2021-04-22 15:39:49.315  INFO 6632 --- [MessageThread_2] a.r.s.s.DefaultRocketMQListenerContainer : consume C0A8640919E818B4AAC26F811AC80010 cost: 0 ms
接收到消息,开始消费..OrderType:已发货,OrderNO:3333333
2021-04-22 15:39:49.315  INFO 6632 --- [MessageThread_2] a.r.s.s.DefaultRocketMQListenerContainer : consume C0A8640919E818B4AAC26F811ACA0014 cost: 0 ms
接收到消息,开始消费..OrderType:已收货,OrderNO:1111111
2021-04-22 15:39:49.315  INFO 6632 --- [MessageThread_2] a.r.s.s.DefaultRocketMQListenerContainer : consume C0A8640919E818B4AAC26F811ACB0018 cost: 0 ms
接收到消息,开始消费..OrderType:已收货,OrderNO:3333333
2021-04-22 15:39:49.316  INFO 6632 --- [MessageThread_2] a.r.s.s.DefaultRocketMQListenerContainer : consume C0A8640919E818B4AAC26F811ACD001C cost: 1 ms

我们看到 发送消息是4个订单状态随机发送 但消息消费时是按照每个订单号的 创建订单—》支付订单—》已发货----》已收货 顺序消费

评论 1 您还未登录,请先 登录 后发表或查看评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:黑客帝国 设计师:我叫白小胖 返回首页

打赏作者

不会吉他的肌肉男不是好的挨踢男

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值