1、定义
同步消息(可靠同步发送):同步发送是指消息发送方发出数据后,会阻塞直到MQ服务方发回响应消息。
应用场景:此种方式应用场景非常广泛,例如重要通知邮件、报名短信通知、营销短信系统等。
2、代码示例
2.1、生产者
package com.wzl.rocketmq.base.producer;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
/**
* 发送同步消息
*/
public class SyncProducerTagA {
public static void sendTagAMessage() throws MQClientException {
//producer
DefaultMQProducer producer = new DefaultMQProducer("syncproducer_taga_group");
//要设置NameServer地址,多个;分割
producer.setNamesrvAddr("192.168.12.121:9876");
//启动
producer.start();
//发送消息
for (int i = 0; i < 10; i++) {
try {
byte[] msgByte = ("Hello world TagA " + i).getBytes(RemotingHelper.DEFAULT_CHARSET);
Message msg = new Message("TopicTest", "TagA", msgByte);
SendResult sendResult = producer.send(msg);
System.out.println("SyncProducer发送消息TagA:" + sendResult);
} catch (Exception e) {
e.printStackTrace();
}
}
//关闭生产者
producer.shutdown();
}
public static void main(String[] args) throws MQClientException {
//发送tagA消息
sendTagAMessage();
}
}
2.2、消费者
package com.wzl.rocketmq.base.consumer;
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.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
/**
* @author wuzelin
* @date 2020-05-03 23:15
*/
public class ConsumerA1 {
public static void main(String[] args) throws MQClientException {
//声明并初始化一个consumer
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer_a1_group");
//要设置NameServer地址,多个;分割
consumer.setNamesrvAddr("192.168.12.121:9876");
//设置consumer所订阅的Topic和Tag,*代表全部的Tag
consumer.subscribe("TopicTest", "TagA");
//消费模式:广播模式消费 OR 集群模式消费
consumer.setMessageModel(MessageModel.CLUSTERING);
//这里设置的是一个consumer的消费策略
//CONSUME_FROM_LAST_OFFSET 默认策略,从该队列最尾开始消费,即跳过历史消息
//CONSUME_FROM_FIRST_OFFSET 从队列最开始开始消费,即历史消息(还储存在broker的)全部消费一遍
//CONSUME_FROM_TIMESTAMP 从某个时间点开始消费,和setConsumeTimestamp()配合使用,默认是半个小时以前
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
//设置一个Listener,主要进行消息的逻辑处理
consumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> {
for (MessageExt messageExt : msgs) {
String messageBody = new String(messageExt.getBody());
System.out.println("ConsumerA1消费消息TagA:" + messageBody);//输出消息内容
}
//返回消费状态
//CONSUME_SUCCESS 消费成功
//RECONSUME_LATER 消费失败,需要稍后重新消费
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
});
//调用start()方法启动consumer
consumer.start();
System.out.println("ConsumerA1 Started.");
}
}