Integration of Alibaba cloud RockMQ and SpringBoot in 2021

preface: The open source version of Rocket is somewhat di...

preface:

The open source version of Rocket is somewhat different from the commercial version of RocketMQ. It studies the commercial version of RocketMQ, which is the official document of Alibaba cloud. It feels a little messy. I don't quite understand. Although there are tutorials on the Internet, most of them are still a little missing. Sometimes they suddenly skip steps and erase some details.

Pre step

Alicloud MQ subscription and generation of permissions for sub Access accounts

Alicloud MQ provisioning

The tutorial on Alibaba cloud MQ (now called Alibaba cloud RocketMQ) Baidu is enough. There are not many records. Please refer to this address http://mtw.so/5Q5nHp , open. PS: because developers are constantly updating the page, the tutorial page is not necessarily exactly the same as the existing page, so don't think hard.

Sub Access account

Alicloud can create two fields for your account to verify your identity. In the figure below, you can enter the application sub account

Jump out of the prompt and select start using the sub-user AccessKey

Click create user

Click OK and you will be asked to verify your mobile phone. Enter the verification code

After creation, you will be given the values of two fields. One is AccessKey ID and AccessKey Secret. You must save them properly in time, although they can be re created

ps: don't forget to give MQ permission to the account, otherwise you can't subscribe and send messages

How to set permissions?

Click Add permission to add the following permissions

Topic and Group creation (on Alibaba cloud console page)

First create an instance and click Create instance

Click OK

Create Group and Topic as prompted, and then fill the names of Group and Topic into the corresponding fields of application.properties

After creating the Group and Topic, you can enter the access point acquisition page

There are two access points corresponding to different access modes. TCP and HTTP, the access mode of TCP Protocol I use here

Only the access address of the public network can be obtained here, and there is no intranet

Start development

SpringBoot integrates alicloud RocketMQ (common message as an example)

Maven project

POM file dependency

<dependencies> <!--Mainly used to write WEB Interface, used here to test MQ Producer of--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--Alibaba cloud ons,Convenient access to cloud services--> <dependency> <groupId>com.aliyun.openservices</groupId> <artifactId>ons-client</artifactId> <version>1.8.4.Final</version> </dependency> <!--Artifact, which is mainly used to output logs@Slf4j--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.16</version> </dependency> <!--For testing, the main purpose is to bring the function with spring Test in container--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>

application.properties

#Before starting the test, please replace the following XXX as your configuration and obtain it from alicloud MQ. See the preceding steps for the specific acquisition method rocketmq.accessKey=xxx rocketmq.secretKey=xxx rocketmq.nameSrvAddr=xxx rocketmq.topic=TpMQTest rocketmq.groupId=GID_MQTEST rocketmq.tag=* rocketmq.orderTopic=XXX rocketmq.orderGroupId=XXX rocketmq.orderTag=*

The configuration class is used to read the value of the corresponding field in application.properties

import com.aliyun.openservices.ons.api.PropertyKeyConst; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import java.util.Properties; @Configuration @ConfigurationProperties(prefix = "rocketmq") public class MqConfig { private String accessKey; private String secretKey; private String nameSrvAddr; private String topic; private String groupId; private String tag; private String orderTopic; private String orderGroupId; private String orderTag; public Properties getMqPropertie() { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.AccessKey, this.accessKey); properties.setProperty(PropertyKeyConst.SecretKey, this.secretKey); properties.setProperty(PropertyKeyConst.NAMESRV_ADDR, this.nameSrvAddr); return properties; } public String getAccessKey() { return accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public String getNameSrvAddr() { return nameSrvAddr; } public void setNameSrvAddr(String nameSrvAddr) { this.nameSrvAddr = nameSrvAddr; } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public String getOrderTopic() { return orderTopic; } public void setOrderTopic(String orderTopic) { this.orderTopic = orderTopic; } public String getOrderGroupId() { return orderGroupId; } public void setOrderGroupId(String orderGroupId) { this.orderGroupId = orderGroupId; } public String getOrderTag() { return orderTag; } public void setOrderTag(String orderTag) { this.orderTag = orderTag; } }

Consumer registration class

The main purpose of the consumer's build is to set the configuration in the configuration file to the ConsumerBean so that it can be started together when Spring is started.

import com.aliyun.openservices.ons.api.MessageListener; import com.aliyun.openservices.ons.api.PropertyKeyConst; import com.aliyun.openservices.ons.api.bean.ConsumerBean; import com.aliyun.openservices.ons.api.bean.Subscription; import com.aliyun.openservices.springboot.example.config.MqConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; import java.util.Properties; //Add the @ Configuration annotation to the project, so that the consumer is started when the service is started @Configuration public class ConsumerClient { @Autowired private MqConfig mqConfig; @Autowired private DemoMessageListener messageListener; @Bean(initMethod = "start", destroyMethod = "shutdown") public ConsumerBean buildConsumer() { ConsumerBean consumerBean = new ConsumerBean(); //configuration file Properties properties = mqConfig.getMqPropertie(); properties.setProperty(PropertyKeyConst.GROUP_ID, mqConfig.getGroupId()); //Fix the number of consumer threads to 20. 20 is the default properties.setProperty(PropertyKeyConst.ConsumeThreadNums, "20"); consumerBean.setProperties(properties); //Subscription relationship Map<Subscription, MessageListener> subscriptionTable = new HashMap<Subscription, MessageListener>(); Subscription subscription = new Subscription(); subscription.setTopic(mqConfig.getTopic()); subscription.setExpression(mqConfig.getTag()); subscriptionTable.put(subscription, messageListener); //Subscribe to multiple topic s, as set above consumerBean.setSubscriptionTable(subscriptionTable); return consumerBean; } }

After registration is completed, enable listening and consume @ Component when there is a message in the message queue. The official Demo of Alibaba cloud does not appear, resulting in that consumers can't consume messages all the time. Later, the news of normal consumption can be added

import com.aliyun.openservices.ons.api.Action; import com.aliyun.openservices.ons.api.ConsumeContext; import com.aliyun.openservices.ons.api.Message; import com.aliyun.openservices.ons.api.MessageListener; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; @Component @Slf4j public class DemoMessageListener implements MessageListener { @Override public Action consume(Message message, ConsumeContext context) { log.info("Receive: " + message); try { //do something.. //Action.CommitMessag confirms the message return Action.CommitMessage; } catch (Exception e) { //Consumption failure return Action.ReconsumeLater; } } }

Producer registration class

import com.aliyun.openservices.ons.api.bean.ProducerBean; import com.aliyun.openservices.springboot.example.config.MqConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ProducerClient { @Autowired private MqConfig mqConfig; @Bean(initMethod = "start", destroyMethod = "shutdown") public ProducerBean buildProducer() { ProducerBean producer = new ProducerBean(); producer.setProperties(mqConfig.getMqPropertie()); return producer; } }

Producer production message tool class

import com.aliyun.openservices.ons.api.Message; import com.aliyun.openservices.ons.api.SendResult; import com.aliyun.openservices.ons.api.bean.ProducerBean; import com.aliyun.openservices.ons.api.exception.ONSClientException; import com.aliyun.openservices.springboot.example.config.MqConfig; import org.springframework.stereotype.Component; /** * @description: <h1>RocketMessageProducer rocketMQ Message producer</h1> * @author: LiRen **/ @Component public class RocketMessageProducer { private static ProducerBean producer; private static MqConfig mqConfig; public RocketMessageProducer(ProducerBean producer, MqConfig mqConfig) { this.producer = producer; this.mqConfig = mqConfig; } /** * @Description: <h2>Production general message</h2> * @author: LiRen */ public static void producerMsg(String tag, String key, String body) { Message msg = new Message(mqConfig.getTopic(), tag, key, body.getBytes()); long time = System.currentTimeMillis(); try { SendResult sendResult = producer.send(msg); assert sendResult != null; System.out.println(time + " Send mq message success.Topic is: " + msg.getTopic() + " Tag is: " + msg.getTag() + " Key is: " + msg.getKey() + " msgId is: " + sendResult.getMessageId()); } catch (ONSClientException e) { e.printStackTrace(); System.out.println(time + " Send mq message failed. Topic is:" + msg.getTopic()); // TODO sending failed } } }

WEB interface, test Controller class

/** * ClassName: ProducerController <br/> * Description: <br/> * date: 2021/11/3 11:05<br/> * * @author Hesion<br /> * @version * @since JDK 1.8 */ import com.aliyun.openservices.springboot.example.normal.RocketMessageProducer; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * Test producer * @author: hesion * @create: 2021-11-03 11:05 **/ @RestController public class ProducerController { /** * rocketmq demo */ @RequestMapping(value = {"/useRocketMQ"}, method = RequestMethod.GET) public String useRocketMQ() { RocketMessageProducer.producerMsg("RocketProdTagTest","RocketProdKeyTest","RocketProdBodyTest"); return "Request succeeded!"; } }

All right, the code is below

Gitee code address

3 November 2021, 06:09 | Views: 5537

Add new comment

For adding a comment, please log in
or create account

0 comments