当前位置:网站首页>Subscribe to Alibaba demo send business messages
Subscribe to Alibaba demo send business messages
2022-04-23 12:56:00 【Play ha ha 527】
Tips : When the article is finished , Directories can be generated automatically , How to generate it, please refer to the help document on the right
Commercial Ali MQ Ordinary message sending subscription Demo
Preface
Tips : The following is the main body of this article , The following cases can be used for reference
One 、 Send a normal message
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import java.util.Properties;
public class ProducerTest {
public static void main(String[] args) {
Properties properties = new Properties();
// AccessKeyId Alicloud Authentication , Get the information from Alibaba cloud user information management console .
properties.put(PropertyKeyConst.AccessKey,"XXX");
// AccessKeySecret Alicloud Authentication , Get the information from Alibaba cloud user information management console .
properties.put(PropertyKeyConst.SecretKey, "XXX");
// Set send timeout , Company : millisecond .
properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, "3000");
// Set up TCP Access domain name , Enter the message queue RocketMQ View in the access point area of the console instance details page .
properties.put(PropertyKeyConst.NAMESRV_ADDR, "XXX");
Producer producer = ONSFactory.createProducer(properties);
// Before sending a message , Must call start Method to start Producer, Just one call .
producer.start();
// Loop messages .
for (int i = 0; i < 100; i++){
Message msg = new Message(
// Ordinary messages belong to Topic, Do not use the of ordinary messages Topic To send and receive other types of messages .
"TopicTestMQ",
// Message Tag Can be understood as Gmail The label in , Recategorize messages , convenient Consumer Specify filter conditions in message queue RocketMQ Version of server filtering .
"TagA",
// Message Body It can be any binary form of data , Message queue RocketMQ The version does not do any intervention .
// need Producer And Consumer Agree on a consistent way to serialize and deserialize .
"Hello MQ".getBytes());
// Set the business critical properties that represent the message , Please be as global and unique as possible .
// In order to facilitate you to receive messages in the case of normal , It can be through message queue RocketMQ The version console queries the message and reissues it .
// Be careful : No setting will not affect the normal sending and receiving of messages .
msg.setKey("ORDERID_" + i);
try {
SendResult sendResult = producer.send(msg);
// Synchronous messaging , As long as we don't throw exceptions, we will succeed .
if (sendResult != null) {
System.out.println(new Date() + " Send mq message success. Topic is:" + msg.getTopic() + " msgId is: " + sendResult.getMessageId());
}
}
catch (Exception e) {
// Message delivery failed , Need to retry processing , You can resend the message or persist the data for compensation processing .
System.out.println(new Date() + " Send mq message failed. Topic is:" + msg.getTopic());
e.printStackTrace();
}
}
// Before the app exits , The destruction Producer object .
// Be careful : If you don't destroy it, there's no problem .
producer.shutdown();
}
}
Two 、 Subscribe to general news
Subscription mode
Message queue RocketMQ Version supports the following two subscription methods :
Cluster subscription
The same Group ID All marked Consumer Average share of consumption news . For example, a Topic Yes 9 Bar message , One Group ID Yes 3 individual Consumer example , Then, in the cluster consumption mode, each instance is allocated equally , Consume only... Of them 3 Bar message . The settings are as follows .
// Cluster subscription mode settings ( Without setting , The default is cluster subscription mode ).
properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.CLUSTERING);
Broadcast subscription
The same Group ID All marked Consumer They will each consume a message once . For example, a Topic Yes 9 Bar message , One Group ID Yes 3 individual Consumer example , Then in the broadcast consumption mode, each instance will consume its own 9 Bar message . The settings are as follows .
// Broadcast subscription mode settings .
properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.BROADCASTING);
Message queue RocketMQ Version supports the following two message acquisition methods :
Push: The message is sent by the message queue RocketMQ Push version to Consumer.Push Under way , Message queue RocketMQ The version also supports batch consumption , Batch messages can be uniformly pushed to Consumer Consumption .
Pull: Message by Consumer Active from message queue RocketMQ Plate pulling .
Here we show only Push Send message by
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Consumer;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import java.util.Properties;
public class ConsumerTest {
public static void main(String[] args) {
Properties properties = new Properties();
// You created Group ID.
properties.put(PropertyKeyConst.GROUP_ID, "XXX");
// AccessKey ID Alicloud Authentication , In Ali cloud RAM Console creation .
properties.put(PropertyKeyConst.AccessKey, "XXX");
// Accesskey Secret Alicloud Authentication , In Alibaba cloud service RAM Console creation .
properties.put(PropertyKeyConst.SecretKey, "XXX");
// Set up TCP Access domain name , Enter the instance details page of the console TCP Protocol client access point area view .
properties.put(PropertyKeyConst.NAMESRV_ADDR, "XXX");
// Subscription cluster mode ( Default ).
// properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.CLUSTERING);
// Broadcast subscription mode .
// properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.BROADCASTING);
Consumer consumer = ONSFactory.createConsumer(properties);
consumer.subscribe("TopicTestMQ", "TagA||TagB", new MessageListener() {
// Subscribe to multiple Tag.
public Action consume(Message message, ConsumeContext context) {
System.out.println("Receive: " + message);
return Action.CommitMessage;
}
});
// Subscribe to another Topic, To unsubscribe from this Topic, Please delete the subscription code in this section , Restart the consumer .
consumer.subscribe("TopicTestMQ-Other", "*", new MessageListener() {
// Subscribe to all Tag.
public Action consume(Message message, ConsumeContext context) {
System.out.println("Receive: " + message);
return Action.CommitMessage;
}
});
consumer.start();
System.out.println("Consumer Started");
}
}
summary
版权声明
本文为[Play ha ha 527]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230615230996.html
边栏推荐
- 21 days learning mongodb notes
- Servlet监听器&过滤器介绍
- Summary of JVM knowledge points - continuously updated
- 【csnote】ER图
- 云原生KubeSphere部署Redis
- Record some NPM related problems (messy records)
- Remote sensing image classification and recognition system based on convolutional neural network
- 5 free audio material websites, recommended collection
- 进程虚拟地址空间区域划分
- Can I take the CPDA data analyst certificate for 0 foundation
猜你喜欢
实现一个盒子在父盒子中水平垂直居中的几种“姿势”
Software testing weekly (issue 68): the best way to solve difficult problems is to wait and see the changes and push the boat with the current.
【每日一题】棋盘问题
Unable to create servlet under SRC subfile of idea
Kubernetes 入门教程
The accuracy and speed are perfectly balanced, and the latest image segmentation SOTA model is released!!!
box-sizing
软件测试周刊(第68期):解决棘手问题的最上乘方法是:静观其变,顺水推舟。
SSM框架系列——注解开发day2-2
No idle servers? Import OVF image to quickly experience smartx super fusion community version
随机推荐
NPDP | how can product managers not be excluded by programmers?
Use source insight to view and edit source code
Remote access to raspberry pie at home (Part 1)
SSM framework series - JUnit unit test optimization day2-3
31. Next arrangement
BaseRecyclerViewAdapterHelper 实现下拉刷新和上拉加载
Record the problems encountered in using v-print
精度、速度完美平衡,最新图像分割SOTA模型重磅发布!!!
Unlock openharmony technology day! The annual event is about to open!
Web17 -- use of El and JSTL
云原生KubeSphere部署Redis
梳理網絡IP代理的幾大用途
Ad20 supplementary note 3 - shortcut key + continuous update
BUUCTF WEB [BUUCTF 2018]Online Tool
21 days learning mongodb notes
BUUCTF WEB [BJDCTF2020]ZJCTF,不过如此
Homomorphic encryption technology learning
SSM framework series - annotation development day2-2
Summary of JVM knowledge points - continuously updated
mysql支持ip访问