RocketMQ ordinary message combat drill

Work together to create and grow together! This is the 23rd day of my participation in the "Nuggets Daily New Plan · August Update Challenge", click to view the details of the event

I have studied the source code of RocketMQ before, and here are examples of demos of various message sending and consumption, which are convenient for future use of CV.

Related configuration, installation and startup are explained in this article juejin.cn/post/712688…

Ordinary messages are sent synchronously

A synchronous message means that after a message is sent, it waits synchronously , and will not continue to send the next message until it receives a successful response from the Broker . This method can ensure that the message is successfully sent to the Broker, and some important messages can use this method, such as important notifications.

public static void main(String[] args) throws Exception {
    //实例化消息生产者对象
    DefaultMQProducer producer = new DefaultMQProducer("group_luke");
    //设置NameSever地址
    producer.setNamesrvAddr("127.0.0.1:9876");
    //启动Producer实例
    producer.start();
    for (int i = 0; i < 10; i++) {
        Message msg = new Message("topic_luke", "tag", ("这是第"+i+"条消息。").getBytes(StandardCharsets.UTF_8));

        //同步发送方式
        SendResult send = producer.send(msg);
        //确认返回
        System.out.println(send);
    }
    //关闭producer
    producer.shutdown();
}
复制代码

Asynchronous sending of ordinary messages

An asynchronous message sender sends a second message without waiting for a response from the receiver after sending a message . The sender receives the server response through the callback interface and processes the response result.

public static void main(String[] args) throws Exception {
    //实例化消息生产者对象
    DefaultMQProducer producer = new DefaultMQProducer("group_luke");
    //设置NameSever地址
    producer.setNamesrvAddr("127.0.0.1:9876");
    //启动Producer实例
    producer.start();
    for (int i = 0; i < 10; i++) {
        Message msg = new Message("topic_luke", "tag", ("这是第"+i+"条消息。").getBytes(StandardCharsets.UTF_8));
        //SendCallback会接收异步返回结果的回调
        producer.send(msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println(sendResult);
            }
            @Override
            public void onException(Throwable throwable) {
                throwable.printStackTrace();
            }
        });
    }
    //若是过早关闭producer,会抛出The producer service state not OK, SHUTDOWN_ALREADY的错
    Thread.sleep(10000);
    //关闭producer
    producer.shutdown();
}
复制代码

One-way sending of ordinary messages

Single-item sending does not care about the result of the sending, only sends the request without waiting for the response. Sending messages takes very little time.

public static void main(String[] args) throws Exception {
    //实例化消息生产者对象
    DefaultMQProducer producer = new DefaultMQProducer("group_luke");
    //设置NameSever地址
    producer.setNamesrvAddr("127.0.0.1:9876");
    //启动Producer实例
    producer.start();
    for (int i = 0; i < 10; i++) {
        Message msg = new Message("topic_luke", "tag", ("这是第"+i+"条消息。").getBytes(StandardCharsets.UTF_8));

        //同步发送方式
        producer.sendOneway(msg);
    }
    //关闭producer
    producer.shutdown();
}
复制代码

Cluster consumption mode

Consumers consume messages in a load -balancing manner. Multiple consumers under the same group consume messages in the Queue together, and each consumer processes different messages. Each Consumer instance in a Consumer Group consumes messages together, that is, a message will only be delivered to one instance under a Group, and only consumed once.

For example, a topic has 3 queues, and one Consumer Group has 3 instances, then each instance consumes only 1 of the queues. The cluster consumption mode is the default consumption mode of consumers.

public static void main(String[] args) throws Exception {
    //实例化消息消费者
    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group_luke");
    //指定nameserver地址
    consumer.setNamesrvAddr("127.0.0.1:9876");
    //订阅topic,"*"表示所有tag
    consumer.subscribe("topic_luke","*");

    consumer.setMessageModel(MessageModel.CLUSTERING);
    // 注册回调实现类来处理从broker拉取回来的消息
    consumer.registerMessageListener(new MessageListenerConcurrently() {
        @SneakyThrows
        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
            for (MessageExt msg : msgs) {
                System.out.println(new String(msg.getBody()));
            }
            // 标记该消息已经被成功消费
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });
    // 启动消费者实例
    consumer.start();
    System.out.printf("Consumer Started.%n");
}
复制代码

Broadcast consumption model

In the broadcast consumption mode, the message is delivered to each Consumer instance under a Group. That is to say, the message will also be consumed once by each Consumer in the Group. In fact, each consumer instance under a consumer group gets each Message Queue under the topic to pull and cancel the consumption. So the message will be delivered to each consumer instance.

public static void main(String[] args) throws Exception {
    //实例化消息消费者
    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group_luke");
    //指定nameserver地址
    consumer.setNamesrvAddr("127.0.0.1:9876");
    //订阅topic,"*"表示所有tag
    consumer.subscribe("topic_luke","*");

    consumer.setMessageModel(MessageModel.BROADCASTING);
    // 注册回调实现类来处理从broker拉取回来的消息
    consumer.registerMessageListener(new MessageListenerConcurrently() {
        @SneakyThrows
        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
            for (MessageExt msg : msgs) {
                System.out.println(new String(msg.getBody()));
            }
            // 标记该消息已经被成功消费
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });
    // 启动消费者实例
    consumer.start();
    System.out.printf("Consumer Started.%n");
}
复制代码

Guess you like

Origin juejin.im/post/7134336877431586830