// 5.发送消息
SendResult result = producer.send(msgs);
// 发送状态
SendStatus status = result.getSendStatus();
System.out.println(“发送结果:” + result);
// 线程睡1秒
TimeUnit.SECONDS.sleep(1);
// 6.关闭生产者producer
producer.shutdown();
System.out.println(“生产者关闭”);
}
}
效果:

第四节:批量消息消费者
============
public class Consumer {
public static void main(String[] args) throws Exception {
//1.创建消费者Consumer,制定消费者组名
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(“demo_consumer_order_group”);
//2.指定Nameserver地址
consumer.setNamesrvAddr(“192.168.88.131:9876”);
//消息拉取最大条数
consumer.setConsumeMessageBatchMaxSize(2);
//3.订阅主题Topic和Tag
consumer.subscribe(“Topic_batch_demo”, “*”);
//4.设置回调函数,处理消息
consumer.registerMessageListener(new MessageListenerOrderly() {
//接受消息内容
@Override
public ConsumeOrderlyStatus consumeMessage(List msgs, ConsumeOrderlyContext consumeOrderlyContext) {
for (MessageExt msg : msgs) {
try {
//获取主题
String topic = msg.getTopic();
//获取标签
String tags = msg.getTags();
//获取信息
byte[] body = msg.getBody();
String result = new String(body, RemotingHelper.DEFAULT_CHARSET);
System.out.println(“Consumer消费信息:topic:” + topic + “,tags:”+tags+
“,result”+ result);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
//重试
return ConsumeOrderlyStatus.SUSPEND_CU

本文通过实例展示了如何使用RocketMQ实现批量消息的生产与消费。内容包括批量消息生产者和消费者的代码实现,以及针对超过4MB消息的拆分工具类。此外,还提供了Java开发学习资料和进阶学习笔记。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



