1. 可靠同步發(fā)送
同步發(fā)送是指消息發(fā)送方發(fā)出數(shù)據(jù)后宴偿,會(huì)在收到接收方發(fā)回響應(yīng)之后才發(fā)下一個(gè)數(shù)據(jù)包的通訊方式。
調(diào)用DefaultMQProducer
的send
方法
public class SyncProducer {
public static void main(String[] args) throws Exception {
//Instantiate with a producer group name.
DefaultMQProducer producer = new
DefaultMQProducer("example_group_name");
//Launch the instance.
producer.start();
for (int i = 0; i < 100; i++) {
//Create a message instance, specifying topic, tag and message body.
Message msg = new Message("TopicTest" ,
"TagA" ,
("Hello RocketMQ " +
i).getBytes(RemotingHelper.DEFAULT_CHARSET)
/* Message body */
);
//Call send message to deliver message to one of brokers.
SendResult sendResult = producer.send(msg);
System.out.printf("%s%n", sendResult);
}
//Shut down once the producer instance is not longer in use.
producer.shutdown();
}
}
2. 可靠異步發(fā)送
異步發(fā)送是指發(fā)送方發(fā)出數(shù)據(jù)后藤肢,不等接收方發(fā)回響應(yīng),接著發(fā)送下個(gè)數(shù)據(jù)包的通訊方式。 MQ 的異步發(fā)送托慨,需要用戶(hù)實(shí)現(xiàn)異步發(fā)送回調(diào)接口(SendCallback
)。消息發(fā)送方在發(fā)送了一條消息后暇榴,不需要等待服務(wù)器響應(yīng)即可返回厚棵,進(jìn)行第二條消息發(fā)送蕉世。發(fā)送方通過(guò)回調(diào)接口接收服務(wù)器響應(yīng),并對(duì)響應(yīng)結(jié)果進(jìn)行處理婆硬。
public class AsyncProducer {
public static void main(String[] args) throws Exception {
//Instantiate with a producer group name.
DefaultMQProducer producer = new DefaultMQProducer("example_group_name");
//Launch the instance.
producer.start();
producer.setRetryTimesWhenSendAsyncFailed(0);
for (int i = 0; i < 100; i++) {
final int index = i;
//Create a message instance, specifying topic, tag and message body.
Message msg = new Message("TopicTest",
"TagA",
"OrderID188",
"Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
producer.send(msg, new SendCallback() {
public void onSuccess(SendResult sendResult) {
System.out.printf("%-10d OK %s %n", index,
sendResult.getMsgId());
}
public void onException(Throwable e) {
System.out.printf("%-10d Exception %s %n", index, e);
e.printStackTrace();
}
});
}
//Shut down once the producer instance is not longer in use.
producer.shutdown();
}
}
3. 單向(Oneway)發(fā)送
單向(Oneway)發(fā)送特點(diǎn)為發(fā)送方只負(fù)責(zé)發(fā)送消息狠轻,不等待服務(wù)器回應(yīng)且沒(méi)有回調(diào)函數(shù)觸發(fā),即只發(fā)送請(qǐng)求不等待應(yīng)答彬犯。 此方式發(fā)送消息的過(guò)程耗時(shí)非常短向楼,一般在微秒級(jí)別。
調(diào)用DefaultMQProducer
的sendOneway
方法
public class OnewayProducer {
public static void main(String[] args) throws Exception{
//Instantiate with a producer group name.
DefaultMQProducer producer = new DefaultMQProducer("example_group_name");
//Launch the instance.
producer.start();
for (int i = 0; i < 100; i++) {
//Create a message instance, specifying topic, tag and message body.
Message msg = new Message("TopicTest" /* Topic */,
"TagA" /* Tag */,
("Hello RocketMQ " +
i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
);
//Call send message to deliver message to one of brokers.
producer.sendOneway(msg);
}
//Shut down once the producer instance is not longer in use.
producer.shutdown();
}
}