Getting Started with Spring + RocketMQ

A brief introduction to RocketMQ

RocketMQ is an MQ produced by Alibaba. It has now been donated to Apache and has become a top-level project of Apache. For more information, please  move
to here to introduce a good article to learn RocketMQ:
RocketMQ actual combat (1)
RocketMQ actual combat (2)
RocketMQ actual combat (3)
RocketMQ combat (4)

some instructions

  • The codes given in this article are all code snippets, not complete codes
  • Before reading this article, you need to have the following knowledge:
    • Learn what RocketMQ is and install it
    • Understand JUnit and use it easily
    • Understand Spring and use it easily
    • Understand maven and use it easily

Import related libraries

maven import:

    <!-- junit5 -->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>${junit5.version}</version>
        <scope>test</scope>
    </dependency>
    
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-runner</artifactId>
        <version>${junit5-platform.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-console-standalone</artifactId>
        <version>${junit5-platform.version}</version>
        <scope>test</scope>
    </dependency>
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>
    
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>
    
    <dependency>
        <groupId>org.apache.rocketmq</groupId>
        <artifactId>rocketmq-client</artifactId>
        <version>${rocketmq-client.version}</version>
    </dependency>

Relevant library versions:

<junit5.version>5.1.0</junit5.version>
<junit5-platform.version>1.1.0</junit5-platform.version>
<rocketmq-client.version>4.2.0</rocketmq-client.version>
<spring.version>5.0.4.RELEASE</spring.version>

Create spring configuration file

Create 2 spring configuration files, one for the producer and one for the consumer, the meaning of the relevant parameters will not be introduced

applicationContext-producer.xml producer
<bean id="rocketmqProduct" class="org.apache.rocketmq.client.producer.DefaultMQProducer" init-method="start" destroy-method="shutdown">
    <property name="producerGroup" value="producer1"/>
    <property name="namesrvAddr" value="127.0.0.1:9876"/>
</bean>
applicationContext-consumer.xml consumer
<bean id="consumerImplTest" class="org.klw.test.rocketMqTest.spring.ConsumerTestImpl" />

<bean id="rocketmqConsumer" class="org.apache.rocketmq.client.consumer.DefaultMQPushConsumer" init-method="start" destroy-method="shutdown">
    <property name="consumerGroup" value="concurrent_consumer"/>
    <property name="namesrvAddr" value="127.0.0.1:9876"/>
    <property name="messageListener" ref="consumerImplTest"/>
    <property name="subscription">
        <map>
            <entry key="TopicTest">
                <value>*</value>
            </entry>
        </map>
    </property>
</bean>

You should have noticed that there is an org.klw.test.rocketMqTest.spring.ConsumerTestImpl in the configuration of the consumer, now let's implement it:

public class ConsumerImplTest implements MessageListenerConcurrently {
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
        System.out.println(Thread.currentThread().getName() + " Receive New Messages: " + msgs);
        //返回消费状态
        //CONSUME_SUCCESS 消费成功
        //RECONSUME_LATER 消费失败,需要稍后重新消费
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}

At this point, a simple producer has been prepared, and a simple consumer has also been prepared and implemented. Let's use them.
Next we need to create two JUnit test classes, one for the producer and one for the consumer
producer:

@RunWith(JUnitPlatform.class)  // org.junit.platform.runner.JUnitPlatform
@ExtendWith(SpringExtension.class)  // org.springframework.test.context.junit.jupiter.SpringExtension
@ContextConfiguration({"classpath*:applicationContext-producer.xml"})
public class JUnitProducer {

    @Autowired
    private DefaultMQProducer producer;
    
    @Test
    public void producerData() throws InterruptedException {
    for (int i = 0; i < 10; i++) {  // 发10条消息
        try {
        Message msg = new Message("TopicTest", // topic
            "TagA", // tag
            ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET)// body
        );

        // 调用producer的send()方法发送消息
        // 这里调用的是同步的方式,所以会有返回结果
        SendResult sendResult = producer.send(msg);

        // 打印返回结果,可以看到消息发送的状态以及一些相关信息
        System.out.println(sendResult);
        } catch (Exception e) {
        e.printStackTrace();
        Thread.sleep(1000);
        }
    }
    }
    
}

consumer:

@RunWith(JUnitPlatform.class)
@ExtendWith(SpringExtension.class)
@ContextConfiguration({"classpath*:applicationContext-consumer.xml"})
public class JUnitConsumer {

    @Test
    public void runConsumer() {
    System.out.println("Consumer Started.");
        
        // 下面的代码把线程阻塞住,这样就可以先运行消费者再运行生产者.当然不要也可以,不要的化就得先运行生产者,
      //再运行消费者,生产者先把消息发送到MQ上,消费者启动后从MQ上拿消息
    synchronized (JUnitConsumer.class) {
        while (true) {
        try {
            JUnitConsumer.class.wait();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        }
    }
    }
    
}

The code is almost done. First run the consumer through JUnit, and then run the producer. In the consumer console, you can see that the message sent by the producer has been printed out.

write at the end

This article just briefly describes how to configure RocketMQ in spring.
The author is also the first time to contact RocketMQ and is learning. Welcome to discuss and learn together.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326021050&siteId=291194637