Lecture 01: Getting Started with RocketMQ

1. What is a message queue?

​ Message queue middleware is an important component in distributed systems. It mainly solves problems such as application coupling, asynchronous messages, and traffic shaving. Achieve high performance, high availability, scalability and eventually consistent architecture. It is an indispensable middleware for large-scale distributed systems. Currently in production environments, the most commonly used message queues include ActiveMQ, RabbitMQ, ZeroMQ, Kafka, MetaMQ, RocketMQ, etc.

Official homepage:RocketMQ · Official website | RocketMQ

Official documents:RocketMQ · Official website | RocketMQ

Download link:Click to download

Visualization tool:Click to download

1.1. Application scenarios

  1. Asynchronous processing
  2. Traffic peak shaving and valley filling (for example: flash sales)
  3. Decoupling microservices

1.2. Comparison of common MQ products

Insert image description here

1.3. Why choose RocketMQ?

The first point is to develop language advantages.

​ RocketMQ is developed using the Java language. Compared with RabbitMQ developed using Erlang, it has a more accessible reading experience and audience. When encountering lower-level problems with RocketMQ, most students who are familiar with Java can read its source code in depth, analyze and troubleshoot problems, and even do it on the basis of the community version二次开发.

Second point, rich advanced features.

​ According to the list of RocketMQ official documents, its advanced features have reached 12 种, such as sequential messages, transaction messages, message filtering, scheduled messages, etc. RocketMQ's rich features can provide us with as many ideas and solutions as possible in complex business scenarios.

The third point is good business prospects.

​ For example, Alibaba has deployed 数百个 RocketMQ 集群,上千个节点 in its production environment. Such a large number of RocketMQ applications in the production environment is enough to show that RocketMQ can indeed withstand the test of the cruel production environment. , and can provide corresponding solutions for complex demand scenarios in the online environment.

​ RocketMQ not only solves Alibaba’s internal needs, but has also been moved to Alibaba Cloud to provide external services as a商业化的产品. The product in Alibaba Cloud is called "Message Queue RocketMQ Edition". Since its commercialization in 2016, the commercial version of RocketMQ has reached a considerable scale. 良好的商业前景,也反向推动着 RocketMQ 在业界的普及,两者相辅相成、相得益彰。

The fourth point is that many major manufacturers endorse it.

​ RocketMQ is now widely used in the internal business of various major manufacturers. Needless to say, Alibaba, the place where it was born, over the years大家所熟悉的双十一促销,在阿里内部就是使用的 RocketMQ 来承载消息, faced with such a huge, RocketMQ delivered a satisfactory answer. Traffic peak

​ For another example, RocketMQ is also the core product in AlibabaTransaction Link. The transaction link is already the core of the core, and this core regards RocketMQ as the core of the core link, which is enough to show the importance it attaches to RocketMQ. At the same time, 字节跳动different internal businesses are also using RocketMQ extensively. As a core component in the main business process, RocketMQ maintains Very high stability and availability very well support the operation and development of the business.

2. How to use RocketMQ

2.1. Build RocketMQ

2.1.1. Download and install Apache RocketMQ

The version of Rocket MQ used in this blog is:rocketmq-all-5.0.0-bin-release. If necessary, you can download it yourself or Looking for a blogger

2.1.2. Configure environment variables

ROCKETMQ_HOME local decompression path

Insert image description here

NAMESRV_ADDR localhost:9876

Insert image description here

2.1.3. Start mqnamesrv

Run powerShell as an administrator, otherwise the service will crash! ! !

If the following prompt appears, the service is started successfully and you can proceed to the next step.

Insert image description here

2.1.4. Start mqbroker

Insert image description here

2.2. Build RocketMQ console

Download the visualization tool zip package, decompress it locally and open it with IDEA

Insert image description here

Run, visit http://localhost:8080/ with the browser

Insert image description here

Console usage instructions reference:https://github.com/eacdy/rocketmq-externals/blob/master/rocketmq-console/doc/1_0_0/UserGuide_CN.md< /span>

3. SpringBoot integrates RocketMQ

SpringBoot version: 2.7.4

3.1、pom.xml

<!--RocketMQ坐标-->
<dependency>
	<groupId>org.apache.rocketmq</groupId>
	<artifactId>rocketmq-spring-boot-starter</artifactId>
	<version>2.2.1</version>
</dependency>

3.2、application.yml

server:
  port: 8083
rocketmq:
  #RocketMQ Namesrv
  name-server: 127.0.0.1:9876
  producer:
    #生产者分组,RocketMQ必填项,字符可随意
    group: test_mq
    #发送消息超时时间,单位:毫秒。默认为 3000
    send-message-timeout: 3000
    #消息压缩阀值,当消息体的大小超过该阀值后,进行消息压缩。默认为 4 * 1024B
    compress-message-body-threshold: 4096
    #消息体的最大允许大小。。默认为 4 * 1024 * 1024B
    max-message-size: 4194304
    #同步发送消息时,失败重试次数。默认为 2 次。
    retry-times-when-send-failed: 2
    #异步发送消息时,失败重试次数。默认为 2 次。
    retry-times-when-send-async-failed: 2
    #发送消息给 Broker 时,如果发送失败,是否重试另外一台 Broker 。默认为 false
    retry-next-server: false

3.3. Writing producers

package com.rocket.rocketdemo.controller;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    
    

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送普通消息
     * convertAndSend(String destination, Object payload) 发送字符串比较方便
     */
    @RequestMapping("/send")
    public void send(){
    
    
        //参数一:topic
        //参数二:消息内容
        rocketMQTemplate.convertAndSend("test1","test-message");
    }

    /**
     * 发送同步消息
     * Tip:该方法底层调用的是 producer.send()方法,是阻塞的,producer 一定要等到Broker进行了响应后才会返回,才能继续往下执行。如果超时,或者失败了,会触发两次默认的重试。
     */
    @RequestMapping("/testSyncSend")
    public void testSyncSend(){
    
    
        //参数一:topic
        //参数二:消息内容
        SendResult sendResult = rocketMQTemplate.syncSend("test1","同步消息测试");
        System.out.println(sendResult);
    }

    /**
     * 发送异步消息
     * Tip:该方法是非阻塞的,发送结果将由一个回调函数callback进行回调。它与同步发送消息的区别是它在发送消息时多传递了一个SendCallback对象,该方法一调用立马返回,而不需要等待Broker的响应返回。消息发送成功或失败后将回调SendCallback对象的对应方法。
     */
    @RequestMapping("/testASyncSend")
    public void testASyncSend(){
    
    
        //参数一:topic
        //参数二:消息内容
        //参数三:回调
        rocketMQTemplate.asyncSend("test1", "异步消息测试", new SendCallback() {
    
    
            @Override
            public void onSuccess(SendResult sendResult) {
    
    
                System.out.println(sendResult);
            }
            @Override
            public void onException(Throwable throwable) {
    
    
                System.out.println("消息发送异常");
                throwable.printStackTrace();
            }
        });
    }

    /**
     * 发送单向消息
     * Tip:它的发送是单向的,即它不需要等待Broker的响应,只管发送即可,而不论发送成功与失败。通常应用于一些消息不是那么重要,可丢失的场景。
     */
    @RequestMapping("/testOneWay")
    public void testOneWay(){
    
    
        for (int i = 0; i <10 ; i++) {
    
    
            //参数一:topic   如果想添加tag,可以使用"topic:tag"的写法
            //参数二:消息内容
            rocketMQTemplate.sendOneWay("test1","单向消息测试测试下"+i);
        }
    }
}

3.4. Write consumers

package com.rocket.rocketdemo.config;

import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

@Service
//consumerGroup与application.yml中rocketmq.producer.group值一致
//topic与消息生产者发送的消息topic一致
@RocketMQMessageListener(consumerGroup = "test_mq",topic = "test1")
public class RocketMQConsumerListener implements RocketMQListener<String> {
    
    
    @Override
    public void onMessage(String s) {
    
    
        System.out.println("消费消息:"+s);
    }
}

3.5. Testing

To send synchronous messages, use postman to send requests http://localhost:8083/send

Console effect:

Insert image description here

To send asynchronous messages, use postman to send requests http://localhost:8083/testSyncSend

Console effect:

Insert image description here

Guess you like

Origin blog.csdn.net/qzc70919700/article/details/130703093