RocketMQ simple message (reliable synchronization, reliable asynchronous and one-way transmission)

        This article will use RocketMQ to send messages in three ways: reliable synchronization, reliable asynchronous and one-way transmission. And introduce the difference between the load balancing mode and the broadcast mode:

(1) Send messages synchronously:

            Use reliable synchronous transmission in a wide range of scenarios such as important notification messages, SMS notifications, and SMS marketing systems.

 Producer code:

/**
 * 发送同步消息
 * 这种可靠性同步地发送方式使用的比较广泛,比如:重要的消息通知,短信通知。
 */
public class SyncProducer {

    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
        //1.创建消息生产者producer,并指定生产者组名
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer("group1");
        //2.指定NameServer地址
        defaultMQProducer.setNamesrvAddr("192.168.160.131:9876");
        //3.启动producer
        defaultMQProducer.start();
        //4.创建消息对象,指定主题topic、tag和消息体
        for (int i = 0; i < 5; i++) {
            /*
             * 参数一:消息主题Topic
             * 参数二:消息tag
             * 参数三:消息内容
             */
            Message message = new Message("base", "tag1", ("hello world" + i).getBytes());
            //5.发送消息
            SendResult result = defaultMQProducer.send(message);
            System.out.println("result:"+result);
            //睡眠1秒
            TimeUnit.SECONDS.sleep(1);
        }
        //6.关闭生产者producer
        defaultMQProducer.shutdown();

    }

}

(2) Send messages asynchronously

       Asynchronous transmission is usually used in time-sensitive business scenarios.

Producer code:

/**
 * 发送异步消息
 * 异步消息通常用在对响应时间敏感的业务场景,即发送端不能容忍长时间地等待Broker的响应。
 */
@Slf4j
public class AsyncProducer {

    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException {
        //1.创建消息生产者producer,并指定生产者组名
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer("group1");
        //2.指定NameServer地址
        defaultMQProducer.setNamesrvAddr("192.168.160.131:9876");
        //3.启动producer
        defaultMQProducer.start();
        for (int i = 0; i < 10; i++) {
            //4.创建消息对象,指定主题topic、tag和消息体
            /*
             * 参数一:消息主题Topic
             * 参数二:消息tag
             * 参数三:消息内容
             */
            Message message = new Message("base", "tag2", ("hello world" + i).getBytes());
            //5.发送异步消息
            defaultMQProducer.send(message, new SendCallback() {
                //发送成功回调
                @Override
                public void onSuccess(SendResult sendResult) {
                    log.debug("sendResult:{}", sendResult);
                }

                //发送失败回调
                @Override
                public void onException(Throwable throwable) {
                    log.error("throwable:",throwable);
                }
            });
            TimeUnit.SECONDS.sleep(1);
        }
        //6.关闭生产者producer
        defaultMQProducer.shutdown();
    }
}

(3) Send messages in one-way mode

         Unidirectional transmission is used in situations that require medium reliability, such as log collection.

Producer code:

/**
 * 单向发送
 * 这种方式主要用在不特别关心发送结果的场景,例如日志发送
 * @author 13871
 */
@Slf4j
public class OneWayProducer {
    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException {
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer("group1");

        defaultMQProducer.setNamesrvAddr("192.168.160.131:9876");

        defaultMQProducer.start();

        for (int i = 0; i < 10; i++) {
            Message message = new Message("base", "tag3", ("单向消息" + i).getBytes());
            defaultMQProducer.sendOneway(message);
          //  TimeUnit.SECONDS.sleep(1);
        }
        defaultMQProducer.shutdown();
    }
}

Consumer code: (for consumption by the above three producers)

/**
 * 消费者
 */
@Slf4j
public class consumer {
    public static void main(String[] args) throws MQClientException {
        //1.创建消费者Consumer,指定组名
        DefaultMQPushConsumer defaultMQPushConsumer = new DefaultMQPushConsumer("group1");
        //2.指定NameServer地址
        defaultMQPushConsumer.setNamesrvAddr("192.168.160.131:9876");
        //3.订阅主题topic和tag
        defaultMQPushConsumer.subscribe("base", "*");
        //消费者默认是负载均衡,设置成广播模式
        //defaultMQPushConsumer.setMessageModel(MessageModel.BROADCASTING);

        //4.设置回调函数,处理消息
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            //指定消息内容
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt msg:list) {
                    System.out.println("msg:"+new String(msg.getBody()));
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //5.启动consumer
        defaultMQPushConsumer.start();
    }
}

ps: The consumer defaults to load balancing, which can be set to broadcast mode;

If the consumer is load balanced:

consumer1: consumer side

msg:hello world0
msg:hello world3
msg:hello world4

 consumer2: consumer side

msg:hello world1
msg:hello world2

That is, if the default load balancing mode is used, one producer sends 5 messages, and the two consumers consume, which is shared by the two. In turn, one consumes 3 and one consumes 2;

Broadcast mode:

           Because the broadcast mode requires a message to be delivered to all consumer instances under a consumer group, there is no argument that the message is allocated for consumption. In implementation, one of the differences is that when consumers allocate queues, all consumers are divided into all queues.

Take the producer code that sends messages synchronously as an example, start the producer side, then start the two consumer sides, and view the console:

 Producer side, console: (send 5 messages)

result:SendResult [sendStatus=SEND_OK, msgId=24098A1E7A3ECE402C3D4AADC1A10079000018B4AAC2469D7E3D0000, offsetMsgId=C0A8A08300002A9F0000000000019EE5, messageQueue=MessageQueue [topic=base, brokerName=localhost.localdomain, queueId=0], queueOffset=19]
result:SendResult [sendStatus=SEND_OK, msgId=24098A1E7A3ECE402C3D4AADC1A10079000018B4AAC2469D82350001, offsetMsgId=C0A8A08300002A9F0000000000019FBD, messageQueue=MessageQueue [topic=base, brokerName=localhost.localdomain, queueId=1], queueOffset=20]
result:SendResult [sendStatus=SEND_OK, msgId=24098A1E7A3ECE402C3D4AADC1A10079000018B4AAC2469D862D0002, offsetMsgId=C0A8A08300002A9F000000000001A095, messageQueue=MessageQueue [topic=base, brokerName=localhost.localdomain, queueId=2], queueOffset=31]
result:SendResult [sendStatus=SEND_OK, msgId=24098A1E7A3ECE402C3D4AADC1A10079000018B4AAC2469D8A190003, offsetMsgId=C0A8A08300002A9F000000000001A16D, messageQueue=MessageQueue [topic=base, brokerName=localhost.localdomain, queueId=3], queueOffset=30]
result:SendResult [sendStatus=SEND_OK, msgId=24098A1E7A3ECE402C3D4AADC1A10079000018B4AAC2469D8E040004, offsetMsgId=C0A8A08300002A9F000000000001A245, messageQueue=MessageQueue [topic=base, brokerName=localhost.localdomain, queueId=0], queueOffset=20]
17:05:31.676 [NettyClientSelector_1] INFO RocketmqRemoting - closeChannel: close the connection to remote address[192.168.160.131:10911] result: true
17:05:31.684 [NettyClientSelector_1] INFO RocketmqRemoting - closeChannel: close the connection to remote address[192.168.160.131:9876] result: true

 Consumer, console: (two consumers, will consume the same message, both are 5)

msg:hello world0
msg:hello world1
msg:hello world2
msg:hello world3
msg:hello world4

 

Published 186 original articles · praised 146 · 490,000 views

Guess you like

Origin blog.csdn.net/qq_37495786/article/details/105515701