SpringBoot集成RocketMQ实现三种消息发送方式

目录

一、pom文件引入依赖

二、application.yml文件添加内容

三、创建producer生产者

四、创建Consumer消费者(创建两个消费者,所属一个Topic)

五、启动项目测试


RocketMQ 支持3 种消息发送方式: 同步 (sync)、异步(async)、单向(oneway)。

  • 同步:发送者向 MQ 执行发送消息API 时,同步等待,直到消息服务器返回发送结果。
  • 异步:发送者向MQ 执行发送消息API 时,指定消息发送成功后的回调函数,然后调用消息发送API 后,立即返回,消息发送者线程不阻塞,直到运行结束,消息发送成功或失败的回调任务在一个新的线程中返回。
  • 单向:消息发送者向MQ 执行发送消息API 时,直接返回,不等待消息服务器的结果,也不注册回调函数,只管发,不管是否成功存储在消息服务器上。

前提:

运行项目需要具备RocketMQ环境,参考Docker搭建RocketMQ集群

一、pom文件引入依赖

<dependency>
    <groupId>org.apache.rocketmq</groupId>
    <artifactId>rocketmq-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>

二、application.yml文件添加内容

rocketmq:
  name-server: IP:9876  #IP为rocketmq访问的地址
  producer:
    group: first1-group  #事务消息才会用到

三、创建producer生产者

package com.tlxy.lhn.controller.rocketmq;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RocketController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @RequestMapping(value = "/rocket", method = RequestMethod.GET)
    public void noTag() {
        // convertAndSend() 发送普通字符串消息
        rocketMQTemplate.convertAndSend("sendMessage_topic", "Hello Word");
    }

    @RequestMapping(value = "/tagA", method = RequestMethod.GET)
    public void tagA() {
        rocketMQTemplate.convertAndSend("sendMessage_topic:tagA", "hello world tagA");
    }

    @RequestMapping(value = "/tagB", method = RequestMethod.GET)
    public void tagB() {
        rocketMQTemplate.convertAndSend("sendMessage_topic:tagB", "hello world tagB");
    }

    @RequestMapping(value = "/syncSend", method = RequestMethod.GET)
    public void syncSend() {
        String json = "发送同步消息";
        SendResult sendResult = rocketMQTemplate.syncSend("sendMessage_topic:1", json);
        System.out.println(sendResult);
    }

    @RequestMapping(value = "/aSyncSend", method = RequestMethod.GET)
    public void aSyncSend() {
        String json = "发送异步消息";
        SendCallback callback = new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("发送消息成功");
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("发送消息失败");
            }
        };
        rocketMQTemplate.asyncSend("sendMessage_topic", json, callback);
    }

    @RequestMapping(value = "/sendOneWay", method = RequestMethod.GET)
    public void sendOneWay() {
        rocketMQTemplate.sendOneWay("sendMessage_topic", "发送单向消息");
    }
}

四、创建Consumer消费者(创建两个消费者,所属一个Topic)

Consumer1:

package com.tlxy.lhn.controller.rocketmq;

import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

/**
 * topic 是主题
 * consumerGroup 是消费者组,一条消息只能被同一个消费者组里的一个消费者消费。
 * selectorExpression 是用于消息过滤的,以 TAG 方式为例:
 * 默认为 "*",表示不过滤,消费此 topic 下所有消息
 * 配置为 "tagA",表示只消费此 topic 下 TAG = tagA 的消息
 * 配置为 "tagA || tagB",表示消费此 topic 下 TAG = tagA 或  TAG = tagB 的消息,以此类推
 * 消费模式:默认 CLUSTERING ( CLUSTERING:负载均衡 )( BROADCASTING:广播机制 )
 */
@RocketMQMessageListener(topic = "sendMessage_topic",
        consumerGroup = "consumer-group-test1",
//        selectorExpression = "tagA || tagB",
        messageModel = MessageModel.CLUSTERING)
@Component
public class DemoConsumer1 implements RocketMQListener<String> {

    @Override
    public void onMessage(String s) {
        System.out.println("receive message1:" + s);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("处理完成");
    }
}

Consumer2:

package com.tlxy.lhn.controller.rocketmq;

import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

/**
 * topic 是主题
 * consumerGroup 是消费者组,一条消息只能被同一个消费者组里的一个消费者消费。
 * selectorExpression 是用于消息过滤的,以 TAG 方式为例:
 * 默认为 "*",表示不过滤,消费此 topic 下所有消息
 * 配置为 "tagA",表示只消费此 topic 下 TAG = tagA 的消息
 * 配置为 "tagA || tagB",表示消费此 topic 下 TAG = tagA 或  TAG = tagB 的消息,以此类推
 * 消费模式:默认 CLUSTERING ( CLUSTERING:负载均衡 )( BROADCASTING:广播机制 )
 */
@RocketMQMessageListener(topic = "sendMessage_topic",
        consumerGroup = "consumer-group-test1",
        messageModel = MessageModel.CLUSTERING)
@Component
public class DemoConsumer2 implements RocketMQListener<String> {

    @Override
    public void onMessage(String s) {
        System.out.println("receive message2:" + s);
        try {
            Thread.sleep(8000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("处理完成");
    }
}

五、启动项目测试

1、发送同步消息:

 以上输出可以看到:同步消息发送后,消息发送到broker后就返回结果了,消费端还未处理完,两者互互不影响。

2、发送异步消息:

 以上输出:发送者向MQ 执行发送消息API 时,指定消息发送成功后的回调函数,然后调用消息发送API 后,立即返回,消息发送者线程不阻塞,直到运行结束,消息发送成功或失败的回调任务在一个新的线程中返回。

3、发送单向消息:

 以上输出:消息发送者向MQ 执行发送消息API 时,直接返回,不等待消息服务器的结果,也不注册回调函数,只管发,不管是否成功存储在消息服务器上。

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很抱歉,我之前理解有误,MQTT与RocketMQ并不是一样的东西,它们只是不同的消息传递协议。如果您想要在SpringBoot项目中实现RocketMQ和MQTT的消息发送和接收,需要分别集成RocketMQ和MQTT的客户端。 首先,您需要在SpringBoot项目中添加RocketMQ和MQTT客户端的依赖,可以在pom.xml文件中添加如下代码: ```xml <!-- RocketMQ --> <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-client</artifactId> <version>4.8.0</version> </dependency> <!-- MQTT --> <dependency> <groupId>org.eclipse.paho</groupId> <artifactId>org.eclipse.paho.client.mqttv3</artifactId> <version>1.2.5</version> </dependency> ``` 接下来,您需要在application.properties中配置RocketMQ和MQTT的连接信息,例如: ```properties # RocketMQ rocketmq.name-server=127.0.0.1:9876 # MQTT mqtt.username=admin mqtt.password=admin mqtt.url=tcp://127.0.0.1:1883 ``` 然后,您可以通过注入RocketMQ的DefaultMQProducer和DefaultMQPushConsumer来实现消息发送和接收。例如: ```java // RocketMQ @Autowired private DefaultMQProducer producer; public void sendMessage(String topic, String message) throws Exception { Message msg = new Message(topic, message.getBytes(StandardCharsets.UTF_8)); SendResult sendResult = producer.send(msg); System.out.printf("%s%n", sendResult); } @Autowired private DefaultMQPushConsumer consumer; public void receiveMessage(String topic) throws Exception { consumer.subscribe(topic, "*"); consumer.registerMessageListener(new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs); return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); consumer.start(); } // MQTT @Autowired private MqttClient mqttClient; public void sendMessage(String topic, String message) throws Exception { MqttMessage mqttMessage = new MqttMessage(message.getBytes()); mqttMessage.setQos(2); mqttClient.publish(topic, mqttMessage); } @MessageEndpoint public class MqttMessageReceiver { @Autowired private MyService myService; @ServiceActivator(inputChannel = "mqttInputChannel") public void receiveMessage(String message) { myService.handleMessage(message); } } ``` 以上代码中,sendMessage方法用于发送消息,receiveMessage方法用于接收消息。使用DefaultMQProducer和DefaultMQPushConsumer可以很方便地发送和接收RocketMQ消息,使用MqttClient和MqttMessageReceiver可以很方便地发送和接收MQTT消息。 这就是SpringBoot集成RocketMQ和MQTT实现消息发送和接收的基本流程,希望对您有所帮助。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值