RocketMq学习笔记03---JAVA代码实现RocketMQ消息发送和接收
1.引入rocketmq的依赖
<dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-client</artifactId> <version>4.3.0</version> </dependency>
2.启动Rocketmq-dashboard管理台
具体参见:https://www.cnblogs.com/luckyplj/p/16007605.html
3. 向RocketMq发送消息
3.1 配置RocketMq发送消息的相关属性
rocketmq.address=127.0.0.1:9876 rocketmq.producer.groupId=FLEP_FILE rocketmq.producer.sendMsgTimeout=10000 rocketmq.producer.retryWhenSendFailed=3
3.2 发送fileId和createDate等内容到RocketMq
package com.ttbank.flep.core.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.ttbank.flep.core.util.PropertyUtil; import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer; import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext; import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; import org.apache.rocketmq.client.exception.MQBrokerException; import org.apache.rocketmq.client.exception.MQClientException; import org.apache.rocketmq.client.producer.DefaultMQProducer; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.common.message.Message; import org.apache.rocketmq.common.message.MessageExt; import org.apache.rocketmq.remoting.common.RemotingHelper; import org.apache.rocketmq.remoting.exception.RemotingException; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Random; /** * @Author lucky * @Date 2022/3/15 15:50 */ @Slf4j @RestController @RequestMapping("/rocketmq") public class RocketMqController { @PostMapping("/sendMq") public void sendMq(){ // 1 获取消息生产者 DefaultMQProducer defaultMQProducer = getRocketMqProducer(); // 2 启动生产者 try { defaultMQProducer.start(); } catch (MQClientException e) { e.printStackTrace(); } // 3 构建消息对象,主要是设置消息的主题、标签、内容 JSONObject jsonObject = generateMsgContent(); Message message = new Message("lucky-topic", "lucky-tag", jsonObject.toString().getBytes()); // 4 发送消息 SendResult result = null; try { result = defaultMQProducer.send(message); } catch (Exception e) { e.printStackTrace(); } System.out.println("SendResult-->" + result); // TODO 6 关闭生产者 defaultMQProducer.shutdown(); } /** * 读取配置文件中设置的rocketmq相关属性,创建消息生产者 */ private DefaultMQProducer getRocketMqProducer(){ String mqAddress = PropertyUtil.getProperties("rocketmq.address"); String groupId = PropertyUtil.getProperties("rocketmq.producer.groupId"); String msgTimeout = PropertyUtil.getProperties("rocketmq.producer.sendMsgTimeout"); String retryWhenSendFailed = PropertyUtil.getProperties("rocketmq.producer.retryWhenSendFailed"); // 1 创建消息生产者,指定生成组名 DefaultMQProducer defaultMQProducer = new DefaultMQProducer(groupId); // 2 指定NameServer的地址 defaultMQProducer.setNamesrvAddr(mqAddress); // 3 设置消息超时时间 defaultMQProducer.setSendMsgTimeout(Integer.parseInt(msgTimeout)); // 4 同步发送消息,如果SendMsgTimeout时间内没有发送成功,则重试retryWhenSendFailed次 defaultMQProducer.setRetryTimesWhenSendFailed(Integer.parseInt(retryWhenSendFailed)); return defaultMQProducer; } /** * 模拟生成消息体的内容 */ private JSONObject generateMsgContent(){ JSONObject jsonObject=new JSONObject(); Random random=new Random(); int fileId = random.nextInt(10000); jsonObject.put("fileId",String.valueOf(fileId)); LocalDateTime localDateTime=LocalDateTime.now(); String fileCreateDate = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); jsonObject.put("fileCreateDate",fileCreateDate ); return jsonObject; } }
3.3 postman测试
控制台输出:
2022-03-16 17:39:19.776 | INFO | http-nio-7010-exec-3 | com.ttbank.flep.core.interceptor.AccessLogInterceptor:18 | [] -进入到拦截器AccessLogInterceptor中:preHandle() 方法 2022-03-16 17:39:19.780 | INFO | http-nio-7010-exec-3 | com.ttbank.flep.core.interceptor.AccessLogInterceptor:20 | [] -接收到来自[null]请求 SendResult-->SendResult [sendStatus=SEND_OK, msgId=AC1210C6D1C818B4AAC2510941600002, offsetMsgId=AC1210C600002A9F000000000000027D, messageQueue=MessageQueue [topic=lucky-topic, brokerName=LAPTOP-NCTKP3GJ, queueId=2], queueOffset=0] 2022-03-16 17:39:21.076 | INFO | NettyClientSelector_1 | RocketmqRemoting:95 | [] -closeChannel: close the connection to remote address[127.0.0.1:9876] result: true 2022-03-16 17:39:21.077 | INFO | NettyClientSelector_1 | RocketmqRemoting:95 | [] -closeChannel: close the connection to remote address[172.18.16.198:10911] result: true 2022-03-16 17:39:21.078 | INFO | NettyClientSelector_1 | RocketmqRemoting:95 | [] -closeChannel: close the connection to remote address[172.18.16.198:10909] result: true
3.4 Rocketmq-dashboard管理台查看消息内容
4.从RocketMq接收消息
4.1 配置RocketMq发送消息的相关属性
rocketmq.address=127.0.0.1:9876
rocketmq.consumer.consumerGroup=FLEP-CONSUMER-TEST
4.2 java代码
package com.ttbank.flep.core.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.ttbank.flep.core.util.PropertyUtil; import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer; import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext; import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; import org.apache.rocketmq.client.exception.MQBrokerException; import org.apache.rocketmq.client.exception.MQClientException; import org.apache.rocketmq.client.producer.DefaultMQProducer; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.common.message.Message; import org.apache.rocketmq.common.message.MessageExt; import org.apache.rocketmq.remoting.common.RemotingHelper; import org.apache.rocketmq.remoting.exception.RemotingException; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Random; /** * @Author lucky * @Date 2022/3/15 15:50 */ @Slf4j @RestController @RequestMapping("/rocketmq") public class RocketMqController { @PostMapping("/receiveMqMsg") public void receiveMqMsg(){ // 1 获取消息消费者 DefaultMQPushConsumer defaultMQPushConsumer = getRocketMqConsumer(); // 2 进行订阅:注册回调函数,编写处理消息的逻辑 defaultMQPushConsumer.registerMessageListener((List<MessageExt> list, ConsumeConcurrentlyContext context) -> { // try catch(throwable)确保不会因为业务逻辑的异常,导致消息出现重复消费的现象 // org.apache.rocketmq.client.impl.consumer.ConsumeMessageConcurrentlyService.ConsumeRequest.run()中会对Throwable进行捕获, //并且返回ConsumeConcurrentlyStatus.RECONSUME_LATER try { System.out.println("收到消息--》" + list); for (MessageExt messageExt : list) { String message=new String(messageExt.getBody(),RemotingHelper.DEFAULT_CHARSET); JSONObject object=JSONObject.parseObject(message); String fileId = (String) object.get("fileId"); String fileCreateDate = (String) object.get("fileCreateDate"); log.info(fileId+":"+fileCreateDate); } } catch (Throwable throwable) { throwable.printStackTrace(); } return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; }); // 5 启动消费者 try { defaultMQPushConsumer.start(); } catch (MQClientException e) { e.printStackTrace(); } System.out.println("消费者启动成功。。。"); } private DefaultMQPushConsumer getRocketMqConsumer(){ String mqAddress = PropertyUtil.getProperties("rocketmq.address"); String consumerGroup = PropertyUtil.getProperties("rocketmq.consumer.consumerGroup"); // 1 创建消费者,指定所属的消费者组名 DefaultMQPushConsumer defaultMQPushConsumer = new DefaultMQPushConsumer(consumerGroup); // 2 指定NameServer的地址 defaultMQPushConsumer.setNamesrvAddr(mqAddress); // 3 指定消费者订阅的主题和标签 try { defaultMQPushConsumer.subscribe("lucky-topic", "*"); } catch (MQClientException e) { e.printStackTrace(); } return defaultMQPushConsumer; } }
4.3 postman测试
控制台输出:
消费者启动成功。。。 收到消息--》[MessageExt [queueId=9, storeSize=225, queueOffset=1, sysFlag=0, bornTimestamp=1647425585106, bornHost=/172.18.16.198:50655, storeTimestamp=1647425585109, storeHost=/172.18.16.198:10911, msgId=AC1210C600002A9F00000000000005FB, commitLogOffset=1531, bodyCRC=1406563058, reconsumeTimes=0, preparedTransactionOffset=0, toString()=Message{topic='lucky-topic', flag=0, properties={MIN_OFFSET=0, MAX_OFFSET=2, CONSUME_START_TIME=1647425739660, UNIQ_KEY=AC1210C6E21818B4AAC2512823D20001, WAIT=true, TAGS=lucky-tag}, body=[123, 34, 102, 105, 108, 101, 67, 114, 101, 97, 116, 101, 68, 97, 116, 101, 34, 58, 34, 50, 48, 50, 50, 45, 48, 51, 45, 49, 54, 32, 49, 56, 58, 49, 51, 58, 48, 53, 34, 44, 34, 102, 105, 108, 101, 73, 100, 34, 58, 34, 56, 55, 52, 55, 34, 125], transactionId='null'}]] 收到消息--》[MessageExt [queueId=1, storeSize=224, queueOffset=0, sysFlag=0, bornTimestamp=1647425511883, bornHost=/172.18.16.198:50575, storeTimestamp=1647425511888, storeHost=/172.18.16.198:10911, msgId=AC1210C600002A9F000000000000051B, commitLogOffset=1307, bodyCRC=1064386839, reconsumeTimes=0, preparedTransactionOffset=0, toString()=Message{topic='lucky-topic', flag=0, properties={MIN_OFFSET=0, MAX_OFFSET=1, CONSUME_START_TIME=1647425739660, UNIQ_KEY=AC1210C6E21818B4AAC2512705CA0000, WAIT=true, TAGS=lucky-tag}, body=[123, 34, 102, 105, 108, 101, 67, 114, 101, 97, 116, 101, 68, 97, 116, 101, 34, 58, 34, 50, 48, 50, 50, 45, 48, 51, 45, 49, 54, 32, 49, 56, 58, 49, 49, 58, 53, 48, 34, 44, 34, 102, 105, 108, 101, 73, 100, 34, 58, 34, 51, 50, 55, 34, 125], transactionId='null'}]] 2022-03-16 18:15:39.660 | INFO | ConsumeMessageThread_2 | com.ttbank.flep.core.controller.RocketMqController:117 | [] -8747:2022-03-16 18:13:05 2022-03-16 18:15:39.660 | INFO | ConsumeMessageThread_1 | com.ttbank.flep.core.controller.RocketMqController:117 | [] -327:2022-03-16 18:11:50
此时,对比Rocketmq-dashboard管理台中查看到的消息内容
参考文献:https://blog.csdn.net/qq_31155349/article/details/108626778
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2020-03-16 深度学习笔记04-卷积神经网络CNN