RocketMQ官方文档地址
https://rocketmq.apache.org/zh/docs/
Client发送消息的方式
Producer与Broker的交互过程
单向发送
- 客户端线程(Producer)使用Netty将消息发送给服务端(Broker)后,交互就结束了
同步发送
- 客户端线程(Producer)将消息发送给服务端(Broker),发送成功后阻塞线程,等待服务端响应
- 服务端(Broker)将响应信息发送给客户端(Producer)
- 客户端(Producer)从本地缓存中获取收到的响应对应的消息,并唤醒消息对应的线程去执行收到响应后的动作
异步发送
- 客户端线程(Producer)将消息加入DefaultMQProducerImpl的asyncSenderExecutor中后,发送消息的方法就结束了
- asyncSenderExecutor线程池将需要发送的消息发送给服务端(Broker)
- 服务端(Broker)将响应信息发送给客户端(Producer),Producer收到响应后从本地缓存中获取对应的消息,并执行该消息对应的回调方法
示例
示例都是来源于源码,源码地址:https://gitee.com/apache/rocketmq?_from=gitee_search
单向发送
DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
// Specify name server addresses.
producer.setNamesrvAddr("localhost:9876");
//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(StandardCharsets.UTF_8) /* Message body */
);
//Call send message to deliver message to one of brokers.
producer.sendOneway(msg);
}
//Wait for sending to complete
Thread.sleep(5000);
producer.shutdown();
同步发送
DefaultMQProducer producer = new DefaultMQProducer(PRODUCER_GROUP);
producer.setNamesrvAddr(DEFAULT_NAMESRVADDR);
producer.start();
for (int i = 0; i < 128; i++) {
try {
Message msg = new Message(TOPIC, TAG, "OrderID188", "Hello world".getBytes(StandardCharsets.UTF_8));
// 消息和过期时间,也可以这样producer.send(msg)过期时间为producer的默认时间3000ms
SendResult sendResult = producer.send(msg, 1000);
System.out.printf("%s%n", sendResult);
} catch (Exception e) {
e.printStackTrace();
}
}
producer.shutdown();
异步发送
DefaultMQProducer producer = new DefaultMQProducer("Jodie_Daily_test");
producer.setNamesrvAddr("localhost:9876");
producer.start();
// suggest to on enableBackpressureForAsyncMode in heavy traffic, default is false
producer.setEnableBackpressureForAsyncMode(true);
producer.setRetryTimesWhenSendAsyncFailed(0);
int messageCount = 100;
final CountDownLatch countDownLatch = new CountDownLatch(messageCount);
for (int i = 0; i < messageCount; i++) {
try {
final int index = i;
Message msg = new Message("TopicTest",
"TagA",
"OrderID188",
"Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
producer.send(msg, new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
countDownLatch.countDown();
System.out.printf("%-10d OK %s %n", index, sendResult.getMsgId());
}
@Override
public void onException(Throwable e) {
countDownLatch.countDown();
System.out.printf("%-10d Exception %s %n", index, e);
e.printStackTrace();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
countDownLatch.await(5, TimeUnit.SECONDS);
producer.shutdown();
源码阅读
DefaultMQProducer
对DefaultMQProducerImpl的包装,几乎DefaultMQProducer的所有方法都是调用DefaultMQProducerImpl的方法来实现
- retryTimesWhenSendFailed:同步模式下消息发送的重试次数,默认为2
- retryTimesWhenSendAsyncFailed:异步模式下的消息发送的重试次数,默认为2
单向发送:sendOneway(Message msg)
在返回之前不等待broker的ack,发送失败不重试,具有最大的吞吐量,但是有可能丢失消息,调用DefaultMQProducerImpl的sendOneway方法实现
public void sendOneway(Message msg) throws MQClientException, RemotingException, InterruptedException {
msg.setTopic(withNamespace(msg.getTopic()));
this.defaultMQProducerImpl.sendOneway(msg);
}
同步发送:SendResult send(Message msg, long timeout)
发送消息完成时返回,方法具有内部重试机制,内部在声明失败之前会重试{retryTimesWhenSendFailed}次。因此,broker可能会存在消息重复的问题
public SendResult send(Message msg,
long timeout) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
msg.setTopic(withNamespace(msg.getTopic()));
return this.defaultMQProducerImpl.send(msg, timeout);
}
异步发送:void send(Message msg, SendCallback sendCallback)
将msg放到DefaultMQProducerImpl内部的线程池里执行,msg添加到线程池后,此方法结束,消息发送发送失败最多重试retryTimesWhenSendAsyncFailed次,发送成功或失败后执行sendCallback中的方法
public void send(Message msg,
SendCallback sendCallback) throws MQClientException, RemotingException, InterruptedException {
msg.setTopic(withNamespace(msg.getTopic()));
this.defaultMQProducerImpl.send(msg, sendCallback);
}
DefaultMQProducerImpl
sendOneway(Message msg):单向发送
public void sendOneway(Message msg) throws MQClientException, RemotingException, InterruptedException {
try {
this.sendDefaultImpl(msg, CommunicationMode.ONEWAY, null, this.defaultMQProducer.getSendMsgTimeout());
} catch (MQBrokerException e) {
throw new MQClientException("unknown exception", e);
}
}
SendResult send(Message msg, long timeout):同步发送
public SendResult send(Message msg,
long timeout) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
return this.sendDefaultImpl(msg, CommunicationMode.SYNC, null, timeout);
}
send(Message msg, SendCallback sendCallback):异步发送
public void send(Message msg,
SendCallback sendCallback) throws MQClientException, RemotingException, InterruptedException {
msg.setTopic(withNamespace(msg.getTopic()));
this.defaultMQProducerImpl.send(msg, sendCallback);
}
public void send(Message msg,
SendCallback sendCallback) throws MQClientException, RemotingException, InterruptedException {
send(msg, sendCallback, this.defaultMQProducer.getSendMsgTimeout());
}
// 将需要发送的消息包装成一个Runnable,然后放到线程池中执行
public void send(final Message msg, final SendCallback sendCallback, final long timeout)
throws MQClientException, RemotingException, InterruptedException {
final long beginStartTime = System.currentTimeMillis();
Runnable runnable = new Runnable() {