SpringBoot 2.1.X Integrates RocketMQ4.x

Posted by mr.echo on Tue, 01 Oct 2019 12:10:48 +0200

Actual operations:

1. Start nameser and broker

2. Adding packages

  <properties>
        <!--rocketmq Edition-->
        <rocketmq.version>4.1.0-incubating</rocketmq.version>
    </properties>

    <!--Add to RocketMQ package -->
        <dependency>
            <groupId>org.apache.rocketmq</groupId>
            <artifactId>rocketmq-client</artifactId>
            <version>${rocketmq.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.rocketmq</groupId>
            <artifactId>rocketmq-common</artifactId>
            <version>${rocketmq.version}</version>
        </dependency>

3. Configuration file application.properties

# Group Name of Consumers
apache.rocketmq.consumer.PushConsumer=orderConsumer
# Group name of producer
apache.rocketmq.producer.producerGroup=Producer
# NameServer address
apache.rocketmq.namesrvAddr=127.0.0.1:9876

4. Producer Code

@ PostConstruct: Used on methods that need to be executed after dependency injection to perform any initialization. This method must be invoked before putting the class into the service.
package net.hlx.myspringboot.rocketmq_demo.jms;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class MsgProducer {

    /**
     * Group name of producer
     */
    @Value("${apache.rocketmq.producer.producerGroup}")
    private String producerGroup;

    /**
     * NameServer address
     */
    @Value("${apache.rocketmq.namesrvAddr}")
    private String namesrvAddr;

    //Default producer
    private DefaultMQProducer  producer;

    //Get data
    public DefaultMQProducer getProducer() {
        return producer;
    }

    @PostConstruct
    public void init() {
        //Producer Object
        producer =new DefaultMQProducer(producerGroup);
        //Specify NameServer address, with multiple addresses separated;
        //For example, producer.setNamesrvAddr("192.168.100.141:9876;192.168.100.142:9876;192.168.100.149:9876");

        //Name Service
        producer.setNamesrvAddr(namesrvAddr);

        //
        producer.setVipChannelEnabled(false);
        try {
            /**
             * Producer Objects must be initialized by calling start before they can be used. They can only be initialized once.
             */
            producer.start();
        }catch (Exception ex){

        }
        // producer.shutdown(); generally in the application context, shutdown when closed, with the context listener
    }
}

5. Control class

@RestController
@RequestMapping("/rocketmq/my")
public class OrderController {


    @Autowired  //Injecting message producers
    private MsgProducer service;
    /**
     * Function Description: Wechat Payment Callback Interface
     * @param msg Payment information
     * @param tag Message Secondary Classification
     * @return
     */
    @GetMapping("order")
    public Object order(String msg,String tag) throws UnsupportedEncodingException, InterruptedException, RemotingException, MQClientException, MQBrokerException {

       // Create a message instance with topic, tag, and message body
        Message message=new Message("testTopic",tag,msg.getBytes(RemotingHelper.DEFAULT_CHARSET));

        //Call method ==> return message body
        SendResult result =service.getProducer().send(message);

        System.out.println("Send a response message ID:" + result.getMsgId() + ",Sending State:" + result.getSendStatus());

        return JsonData.buildSuccess();
    }


}

6. Startup==> is just the producer!

7. Consumer Code

package net.hlx.myspringboot.rocketmq_demo.jms;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class MsgConsumer {

    /**
     * Group name of producer
     */
    @Value("${apache.rocketmq.consumer.PushConsumer}")
    private String consumerGroup;

    /**
     * NameServer address
     */
    @Value("${apache.rocketmq.namesrvAddr}")
    private String namesrvAddr;


    @PostConstruct
    public void defaultMQPushConsumer() {
        //Group Name of Consumers
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(consumerGroup);

        //Specify NameServer address, with multiple addresses separated;
        consumer.setNamesrvAddr(namesrvAddr);
        try {
            //Set the Topic and Tag that consumer subscribes to, * for all Tags
//            consumer.subscribe("testTopic", "*");

            //You can also specify tag s for message filtering
            consumer.subscribe("testTopic", "medicine");

            //CONSUME_FROM_LAST_OFFSET default policy, which starts at the end of the queue and skips historical messages
            //CONSUME_FROM_FIRST_OFFSET starts to consume from the beginning of the queue, that is, all historical messages (also stored in broker) are consumed once.
            consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);

            //MessageListener Orderly This is ordered (orders must be ordered)
            //MessageListener Concurrently is a disorderly, parallel way of processing, much more efficient.
            consumer.registerMessageListener((MessageListenerConcurrently) (list, context) -> {
                try {
                    //Traversal message
                    for (MessageExt messageExt : list) {

                        System.out.println("messageExt: " + messageExt);//Output message content

                        //Get the message content
                        String messageBody = new String(messageExt.getBody(), RemotingHelper.DEFAULT_CHARSET);

                        System.out.println("Consumer Response: msgId : " + messageExt.getMsgId() + ",  msgBody : " + messageBody);//Output message content
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER; //try again later
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; //Consumption success
            });
            consumer.start();   //Open listener
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

8. Restart

9. Specify tag restart

(1) If tag=buy, then consumers will not consume!  

 

(2) If tag=medicine, then consumers consume!  

Topics: Apache