系列五、Java操作RocketMQ简单消息之同步消息

一、概述

        同步消息的特征是消息发出后会有一个返回值,即RocketMQ服务器收到消息后的一个确认,这种方式非常安全,但是性能上却没有那么高,而且在集群模式下,也是要等到所有的从机都复制了消息以后才会返回,适用于重要的消息传递,例如:短信通知

系列五、Java操作RocketMQ简单消息之同步消息_第1张图片

二、案例代码

2.1、pom.xml


  4.0.0

  org.star
  rocketmq-example
  1.0-SNAPSHOT
  jar

  rocketmq-example
  http://maven.apache.org

  
    UTF-8
  

  

    
      org.apache.rocketmq
      rocketmq-client
      4.5.0
    

    
      junit
      junit
      4.13.2
      test
    
    
      com.alibaba
      fastjson
      2.0.25
    
    
      cn.hutool
      hutool-all
      5.8.16
    
    
      org.apache.commons
      commons-collections4
      4.4
    
    
      org.apache.commons
      commons-lang3
      3.12.0
    

    
    
      org.projectlombok
      lombok
      1.18.22
    
    
      org.slf4j
      slf4j-api
      1.7.32
    
    
      ch.qos.logback
      logback-classic
      1.2.10
    

  

  
  
    
      
        org.apache.maven.plugins
        maven-compiler-plugin
        3.8.1
        
          1.8
          1.8
        
      
    
  

2.2、RocketMQConstant

package org.star.constants;

/**
 * @Author: 一叶浮萍归大海
 * @Date: 2023/7/27 16:42
 * @Description:
 */
public class RocketMQConstant {

    /**
     * 配置RocketMQ NameSrv的地址
     */
    public static final String NAME_SERVER_ADDR = "192.168.173.219:9876";

}

2.3、SimpleConsumer

package org.star.simple.consumer;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
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.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.star.constants.RocketMQConstant;

import java.util.List;

/**
 * @Author: 一叶浮萍归大海
 * @Date: 2023/8/25 10:20
 * @Description: 简单消息消费者
 */
@Slf4j
public class SimpleConsumer {

    public static void main(String[] args) throws Exception {
        /**
         * 消费消息分两种
         * (1)拉模式:消费者主动去Broker上拉消息
         * (2)推模式:消费者等待Broker把消息推送过来
         */
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("SimpleMessageGroup");
        consumer.setNamesrvAddr(RocketMQConstant.NAME_SERVER_ADDR);
        consumer.subscribe("SimpleTopic", "*");
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                if (CollectionUtils.isNotEmpty(list)) {
                    String body = StrUtil.utf8Str(list.get(0).getBody());
                    log.info("收到消息 body:{}",body);
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        consumer.start();
        System.out.println("consumer started!");
    }

}

2.4、SyncProducer

package org.star.simple.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.star.constants.RocketMQConstant;

import java.nio.charset.StandardCharsets;

/**
 * @Author: 一叶浮萍归大海
 * @Date: 2023/8/25 10:12
 * @Description: 同步发送:等待消息返回后再继续执行下面的操作
 */
@Slf4j
public class SyncProducer {

    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("SyncProducerGroup");
        producer.setNamesrvAddr(RocketMQConstant.NAME_SERVER_ADDR);
        producer.start();
        for (int i = 0; i < 3; i++) {
            Message message = new Message("SimpleTopic", ("我是第[" + i + "]个简单消息").getBytes(StandardCharsets.UTF_8));
            SendResult sendResult = producer.send(message);
            log.info("第[" + i + "]个简单消息发送成功 sendStatus:{},msgId:{},topic:{}", sendResult.getSendStatus(),sendResult.getMsgId(),sendResult.getMessageQueue().getTopic());
        }
        producer.shutdown();
    }

}

2.5、控制台打印结果

# 生产者端
12:14:32.339 [main] INFO org.star.simple.producer.SyncProducer - 第[0]个简单消息发送成功 sendStatus:SEND_OK,msgId:C0A81FB25D9418B4AAC207C6D9850000,topic:SimpleTopic
12:14:32.343 [main] INFO org.star.simple.producer.SyncProducer - 第[1]个简单消息发送成功 sendStatus:SEND_OK,msgId:C0A81FB25D9418B4AAC207C6D9940001,topic:SimpleTopic
12:14:32.348 [main] INFO org.star.simple.producer.SyncProducer - 第[2]个简单消息发送成功 sendStatus:SEND_OK,msgId:C0A81FB25D9418B4AAC207C6D9970002,topic:SimpleTopic


# 消费者端
12:14:32.337 [ConsumeMessageThread_10] INFO org.star.simple.consumer.SimpleConsumer - 收到消息 body:我是第[0]个简单消息
12:14:32.345 [ConsumeMessageThread_11] INFO org.star.simple.consumer.SimpleConsumer - 收到消息 body:我是第[1]个简单消息
12:14:32.349 [ConsumeMessageThread_12] INFO org.star.simple.consumer.SimpleConsumer - 收到消息 body:我是第[2]个简单消息

你可能感兴趣的:(RocketMQ系列,java-rocketmq,java,rocketmq)