<dependency>
<groupId>org.apache.rocketmqgroupId>
<artifactId>rocketmq-clientartifactId>
<version>4.4.0version>
dependency>
1.创建消息生产者producer,并制定生产者组名
2.指定Nameserver地址
3.启动producer
4.创建消息对象,指定主题Topic、Tag和消息体
5.发送消息
6.关闭生产者producer
1.创建消费者Consumer,制定消费者组名
2.指定Nameserver地址
3.订阅主题Topic和Tag
4.设置回调函数,处理消息
5.启动消费者consumer
这种可靠性同步地发送方式使用的比较广泛,比如:重要的消息通知,短信通知。
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 SyncProducer {
public static void main(String[] args)throws Exception{
//1.创建消费者Consumer,指定消费者组名group1
DefaultMQProducer producer = new DefaultMQProducer("group1");
//2.指定Nameserver地址,集群多台用分号隔开
producer.setNamesrvAddr("192.168.79.203:9876;192.168.79.204:9876");
//3.启动producer
producer.start();
for (int i = 0; i < 100; i++) {
//4.创建消息对象,指定主题Topic、Tag和消息体
/**
* 参数1:消息主题
* 参数2 tag
* 参数3:消息内存
*/
Message msg = new Message("TopicTest" /* Topic */,"TagA" /* Tag */,
("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
//5.发送消息,通过sendResult返回消息是否成功送达
SendResult sendResult = producer.send(msg);
System.out.println("发送结果:"+sendResult);
}
//6.关闭生产者producer, 如果不再发送消息,关闭Producer实例。
producer.shutdown();
}
}
发送结果示例:由于是双主双从的结果,broker主节点负载接收消息,从节点负责消费消息
//sendStatus发送状态、msgId:消息id、offsetMsgId:偏移量id、topic:主题、brokerName:broker节点名称,名字在配置文件中指定、queueId:队列id
发送结果:SendResult [sendStatus=SEND_OK, msgId=C0A80102253018B4AAC2350CD7470000, offsetMsgId=C0A84FCC00002A9F000000000001F521, messageQueue=MessageQueue [topic=TopicTest, brokerName=broker-b, queueId=3], queueOffset=176]
发送结果:SendResult [sendStatus=SEND_OK, msgId=C0A80102253018B4AAC2350CD7D30001, offsetMsgId=C0A84FCB00002A9F000000000001F0F5, messageQueue=MessageQueue [topic=TopicTest, brokerName=broker-a, queueId=0], queueOffset=175]
异步消息通常用在对响应时间敏感的业务场景,即发送端不能容忍长时间地等待Broker的响应。
public class AsyncProducer {
public static void main(String[] args) throws Exception {
// 实例化消息生产者Producer
DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
// 设置NameServer的地址
producer.setNamesrvAddr("localhost:9876");
// 启动Producer实例
producer.start();
producer.setRetryTimesWhenSendAsyncFailed(0);
for (int i = 0; i < 100; i++) {
final int index = i;
// 创建消息,并指定Topic,Tag和消息体
Message msg = new Message("TopicTest",
"TagA",
"OrderID188",
"Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
// SendCallback接收异步返回结果的回调
producer.send(msg, new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
System.out.printf("%-10d OK %s %n", index,
sendResult.getMsgId());
}
@Override
public void onException(Throwable e) {
System.out.printf("%-10d Exception %s %n", index, e);
e.printStackTrace();
}
});
}
// 如果不再发送消息,关闭Producer实例。
producer.shutdown();
}
}
//由于这里集群是双主双从且,master和salve broker都在同一个机器上,性能有限异步发送可能会出现失败的情况
发送结果:SendResult [sendStatus=SEND_OK, msgId=C0A80102539018B4AAC2351A1CFD0005, offsetMsgId=C0A84FCC00002A9F0000000000028CD4, messageQueue=MessageQueue [topic=TopicTest, brokerName=broker-b, queueId=2], queueOffset=235]
发送结果:SendResult [sendStatus=SEND_OK, msgId=C0A80102539018B4AAC2351A1CFD0003, offsetMsgId=C0A84FCC00002A9F0000000000028D82, messageQueue=MessageQueue [topic=TopicTest, brokerName=broker-b, queueId=1], queueOffset=232]
这种方式主要用在不特别关心发送结果的场景,例如日志发送。
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
public class OnewayProducer {
public static void main(String[] args) throws Exception{
// 1.实例化消息生产者Producer
DefaultMQProducer producer = new DefaultMQProducer("group1");
// 2.设置NameServer的地址
producer.setNamesrvAddr("192.168.79.203:9876;192.168.79.204:9876");
// 3.启动Producer实例
producer.start();
for (int i = 0; i < 100; i++) {
// 4.创建消息,并指定Topic,Tag和消息体
Message msg = new Message("TopicTest" /* Topic */,
"TagA" /* Tag */,
("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET)
);
// 5.发送单向消息,没有任何返回结果
producer.sendOneway(msg);
}
// 6.如果不再发送消息,关闭Producer实例。
producer.shutdown();
}
}
单消费者
public class Consumer {
public static void main(String[] args) throws MQClientException {
//1.创建消费者Consumer,制定消费者组名
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
//2.指定Nameserver地址
consumer.setNamesrvAddr("192.168.79.203:9876;192.168.79.204:9876");
//3.订阅主题Topic和Tag
consumer.subscribe("TopicTest", "TagA");
//4.设置回调函数,处理消息
consumer.registerMessageListener(new MessageListenerConcurrently(){
/**
* 接收消息内容的方法
* @param msgs
* @param context 消费者并发消费环境
* @return
*/
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
for (MessageExt msg : msgs) {
System.out.println("msg:" +msg);
byte[] body = msg.getBody();
System.out.println("消息内容:"+new String(body));
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
//5.启动消费者consumer
consumer.start();
}
}
msg:MessageExt [queueId=2, storeSize=178, queueOffset=245, sysFlag=0, bornTimestamp=1662853378585, bornHost=/192.168.79.1:12683, storeTimestamp=1662853379519, storeHost=/192.168.79.203:10911, msgId=C0A84FCB00002A9F000000000002BC9D, commitLogOffset=179357, bodyCRC=613185359, reconsumeTimes=0, preparedTransactionOffset=0, toString()=Message{topic='TopicTest', flag=0, properties={MIN_OFFSET=0, MAX_OFFSET=246, CONSUME_START_TIME=1662853378667, UNIQ_KEY=C0A801024AFC18B4AAC2352776180000, WAIT=true, TAGS=TagA}, body=[72, 101, 108, 108, 111, 32, 82, 111, 99, 107, 101, 116, 77, 81, 32, 48], transactionId='null'}]
msg:MessageExt [queueId=0, storeSize=178, queueOffset=244, sysFlag=0, bornTimestamp=1662853378589, bornHost=/192.168.79.1:12684, storeTimestamp=1662853379524, storeHost=/192.168.79.204:10911, msgId=C0A84FCC00002A9F000000000002C584, commitLogOffset=181636, bodyCRC=1250039395, reconsumeTimes=0, preparedTransactionOffset=0, toString()=Message{topic='TopicTest', flag=0, properties={MIN_OFFSET=0, MAX_OFFSET=245, CONSUME_START_TIME=1662853378667, UNIQ_KEY=C0A801024AFC18B4AAC23527761D0002, WAIT=true, TAGS=TagA}, body=[72, 101, 108, 108, 111, 32, 82, 111, 99, 107, 101, 116, 77, 81, 32, 50], transactionId='null'}]
消息内容:Hello RocketMQ 2
消息内容:Hello RocketMQ 0
消费者采用负载均衡方式消费消息,多个消费者共同消费队列消息,每个消费者处理的消息不同
public class Consumer {
public static void main(String[] args) throws MQClientException {
//1.创建消费者Consumer,制定消费者组名
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
//2.指定Nameserver地址
consumer.setNamesrvAddr("192.168.79.203:9876;192.168.79.204:9876");
//3.订阅主题Topic和Tag
consumer.subscribe("TopicTest", "TagA");
//负载均衡模式消费
consumer.setMessageModel(MessageModel.CLUSTERING);
//4.设置回调函数,处理消息
consumer.registerMessageListener(new MessageListenerConcurrently(){
/**
* 接收消息内容的方法
* @param msgs
* @param context 消费者并发消费环境
* @return
*/
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
for (MessageExt msg : msgs) {
byte[] body = msg.getBody();
System.out.println("消息内容:"+new String(body));
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
//5.启动消费者consumer
consumer.start();
}
}
消费者采用广播的方式消费消息,每个消费者消费的消息都是相同的
public class Consumer {
public static void main(String[] args) throws MQClientException {
//1.创建消费者Consumer,制定消费者组名
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
//2.指定Nameserver地址
consumer.setNamesrvAddr("192.168.79.203:9876;192.168.79.204:9876");
//3.订阅主题Topic和Tag
consumer.subscribe("TopicTest", "TagA");
//广播模式消费
consumer.setMessageModel(MessageModel.BROADCASTING);
//4.设置回调函数,处理消息
consumer.registerMessageListener(new MessageListenerConcurrently(){
/**
* 接收消息内容的方法
* @param msgs
* @param context 消费者并发消费环境
* @return
*/
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
for (MessageExt msg : msgs) {
byte[] body = msg.getBody();
System.out.println("消息内容:"+new String(body));
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
//5.启动消费者consumer
consumer.start();
}
}
消息有序指的是可以按照消息的发送顺序来消费(FIFO)。RocketMQ可以严格的保证消息有序,可以分为分区有序或者全局有序。
顺序消费的原理解析,在默认的情况下消息发送会采取Round Robin轮询方式把消息发送到不同的queue(分区队列);而消费消息的时候从多个queue上拉取消息,这种情况发送和消费是不能保证顺序。但是如果控制发送的顺序消息只依次发送到同一个queue中,消费的时候只从这个queue上依次拉取,则就保证了顺序。当发送和消费参与的queue只有一个,则是全局有序;如果多个queue参与,则为分区有序,即相对每个queue,消息都是有序的。
下面用订单进行分区有序的示例。一个订单的顺序流程是:创建、付款、推送、完成。订单号相同的消息会被先后发送到同一个队列中,消费时,同一个OrderId获取到的肯定是同一个队列。
订单模拟
/**
* 订单的步骤
*/
@Data
public class OrderStep {
private long orderId;
private String desc;
/**
* 生成模拟订单数据
*/
public static List<OrderStep> buildOrders() {
List<OrderStep> orderList = new ArrayList<OrderStep>();
OrderStep orderDemo = new OrderStep();
orderDemo.setOrderId(15103111039L);
orderDemo.setDesc("创建");
orderList.add(orderDemo);
orderDemo = new OrderStep();
orderDemo.setOrderId(15103111065L);
orderDemo.setDesc("创建");
orderList.add(orderDemo);
orderDemo = new OrderStep();
orderDemo.setOrderId(15103111039L);
orderDemo.setDesc("付款");
orderList.add(orderDemo);
orderDemo = new OrderStep();
orderDemo.setOrderId(15103117235L);
orderDemo.setDesc("创建");
orderList.add(orderDemo);
orderDemo = new OrderStep();
orderDemo.setOrderId(15103111065L);
orderDemo.setDesc("付款");
orderList.add(orderDemo);
orderDemo = new OrderStep();
orderDemo.setOrderId(15103117235L);
orderDemo.setDesc("付款");
orderList.add(orderDemo);
orderDemo = new OrderStep();
orderDemo.setOrderId(15103111065L);
orderDemo.setDesc("完成");
orderList.add(orderDemo);
orderDemo = new OrderStep();
orderDemo.setOrderId(15103111039L);
orderDemo.setDesc("推送");
orderList.add(orderDemo);
orderDemo = new OrderStep();
orderDemo.setOrderId(15103117235L);
orderDemo.setDesc("完成");
orderList.add(orderDemo);
orderDemo = new OrderStep();
orderDemo.setOrderId(15103111039L);
orderDemo.setDesc("完成");
orderList.add(orderDemo);
return orderList;
}
}
Producer
public class OrderProducer {
public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
// 1.实例化消息生产者Producer
DefaultMQProducer producer = new DefaultMQProducer("group1");
// 2.设置NameServer的地址
producer.setNamesrvAddr("192.168.79.203:9876;192.168.79.204:9876");
// 3.启动Producer实例
producer.start();
//构建消息集合
List<OrderStep> orderSteps = OrderStep.buildOrders();
for (int i = 0; i < orderSteps.size(); i++) {
OrderStep orderStep = orderSteps.get(i);
Message msg = new Message("OrderTopic", "Order", "KEY" + i, JSON.toJSONString(orderStep).getBytes());
/**
* 参数1:消息内容
* 参数2: 消息队列选择器
* 参数3: 选择队列的业务标识
*/
SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
/**
* @param mqs 队列集合
* @param msg 消息对象
* @param arg 业务标识的参数
* @return
*/
@Override
public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
Long orderId = (Long) arg;
//相同的orderId对应的消息队列是一样的
long index = orderId % mqs.size();
return mqs.get((int) index);
}
}, orderSteps.get(i).getOrderId());//订单id
System.out.println("发送结果:" + sendResult);
}
producer.shutdown();
}
}
public class OrderConsumer {
public static void main(String[] args) throws MQClientException {
//1.创建消费者Consumer,制定消费者组名
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
//2.指定Nameserver地址
consumer.setNamesrvAddr("192.168.79.203:9876;192.168.79.204:9876");
//3.订阅主题Topic和Tag ,* 表示主题下的所有消息都去消费
consumer.subscribe("OrderTopic", "*");
//4.注册消息监听器
consumer.registerMessageListener(new MessageListenerOrderly() {
@Override
public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
for (MessageExt msg : msgs) {
System.out.println(Thread.currentThread().getName()+": "+ new String(msg.getBody()));
}
return ConsumeOrderlyStatus.SUCCESS;
}
});
//5.启动消费者consumer
consumer.start();
}
}
测试结果,在消费者端每个线程负责一个订单流程
ConsumeMessageThread_1: {“desc”:“创建”,“orderId”:15103111065}
ConsumeMessageThread_1: {“desc”:“付款”,“orderId”:15103111065}
ConsumeMessageThread_1: {“desc”:“完成”,“orderId”:15103111065}
ConsumeMessageThread_1: {“desc”:“创建”,“orderId”:15103111065}
ConsumeMessageThread_1: {“desc”:“付款”,“orderId”:15103111065}
ConsumeMessageThread_1: {“desc”:“完成”,“orderId”:15103111065}
ConsumeMessageThread_2: {“desc”:“创建”,“orderId”:15103117235}
ConsumeMessageThread_2: {“desc”:“付款”,“orderId”:15103117235}
ConsumeMessageThread_2: {“desc”:“完成”,“orderId”:15103117235}
ConsumeMessageThread_2: {“desc”:“创建”,“orderId”:15103117235}
ConsumeMessageThread_2: {“desc”:“付款”,“orderId”:15103117235}
ConsumeMessageThread_2: {“desc”:“完成”,“orderId”:15103117235}
比如电商里,提交了一个订单就可以发送一个延时消息,1h后去检查这个订单的状态,如果还是未付款就取消订单释放库存。
public class DelayConsumer {
public static void main(String[] args) throws MQClientException {
//1.创建消费者Consumer,制定消费者组名
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
//2.指定Nameserver地址
consumer.setNamesrvAddr("192.168.79.203:9876;192.168.79.204:9876");
//3.订阅主题Topic和Tag
consumer.subscribe("TopicTest", "*");
//4.设置回调函数,处理消息
consumer.registerMessageListener(new MessageListenerConcurrently(){
/**
* 接收消息内容的方法
* @param msgs
* @param context 消费者并发消费环境
* @return
*/
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
for (MessageExt msg : msgs) {
//当前时间-msg.getStoreTimestamp() 消息存储时间 ==》 延迟时间(单位毫秒)
System.out.println("消息id:"+ msg.getMsgId()+",延迟时间:"+(System.currentTimeMillis()-msg.getStoreTimestamp()));
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
//5.启动消费者consumer
consumer.start();
}
}
public class DelayProducer {
public static void main(String[] args) throws Exception{
// 1.实例化消息生产者Producer
DefaultMQProducer producer = new DefaultMQProducer("group1");
// 2.设置NameServer的地址
producer.setNamesrvAddr("192.168.79.203:9876;192.168.79.204:9876");
// 3.启动Producer实例
producer.start();
for (int i = 0; i < 10; i++) {
// 4.创建消息,并指定Topic,Tag和消息体
Message msg = new Message("TopicTest" /* Topic */,
"TagA" /* Tag */,
("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET)
);
//延时等级参考 org/apache/rocketmq/store/config/MessageStoreConfig.java
//private String messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";
// 设置延时等级3,这个消息将在10s之后发送(现在只支持固定的几个时间,详看delayTimeLevel)
msg.setDelayTimeLevel(3);
// 5.发送单向消息,没有任何返回结果
SendResult sendResult = producer.send(msg);
System.out.println("发送结果:"+sendResult);
}
// 6.如果不再发送消息,关闭Producer实例。
producer.shutdown();
}
}
###3.验证
您将会看到消息的消费比存储时间晚10秒
// org/apache/rocketmq/store/config/MessageStoreConfig.java
private String messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";
现在RocketMq并不支持任意时间的延时,需要设置几个固定的延时等级,从1s到2h分别对应着等级1到18
批量发送消息能显著提高传递小消息的性能。限制是这些批量消息应该有相同的topic,相同的waitStoreMsgOK,而且不能是延时消息。此外,这一批消息的总大小不应超过4MB。
如果您每次只发送不超过4MB的消息,则很容易使用批处理,样例如下:
String topic = "BatchTest";
List<Message> messages = new ArrayList<>();
messages.add(new Message(topic, "TagA", "OrderID001", "Hello world 0".getBytes()));
messages.add(new Message(topic, "TagA", "OrderID002", "Hello world 1".getBytes()));
messages.add(new Message(topic, "TagA", "OrderID003", "Hello world 2".getBytes()));
try {
//批量发送消息
producer.send(messages);
} catch (Exception e) {
e.printStackTrace();
//处理error
}
如果消息的总长度可能大于4MB时,这时候最好把消息进行分割
public class ListSplitter implements Iterator<List<Message>> {
private final int SIZE_LIMIT = 1024 * 1024 * 4;
private final List<Message> messages;
private int currIndex;
public ListSplitter(List<Message> messages) {
this.messages = messages;
}
@Override
public boolean hasNext() {
return currIndex < messages.size();
}
@Override
public List<Message> next() {
int nextIndex = currIndex;
int totalSize = 0;
for (; nextIndex < messages.size(); nextIndex++) {
Message message = messages.get(nextIndex);
int tmpSize = message.getTopic().length() + message.getBody().length;
Map<String, String> properties = message.getProperties();
for (Map.Entry<String, String> entry : properties.entrySet()) {
tmpSize += entry.getKey().length() + entry.getValue().length();
}
tmpSize = tmpSize + 20; // 增加日志的开销20字节
if (tmpSize > SIZE_LIMIT) {
//单个消息超过了最大的限制
//忽略,否则会阻塞分裂的进程
if (nextIndex - currIndex == 0) {
//假如下一个子列表没有元素,则添加这个子列表然后退出循环,否则只是退出循环
nextIndex++;
}
break;
}
if (tmpSize + totalSize > SIZE_LIMIT) {
break;
} else {
totalSize += tmpSize;
}
}
List<Message> subList = messages.subList(currIndex, nextIndex);
currIndex = nextIndex;
return subList;
}
}
//把大的消息分裂成若干个小的消息
ListSplitter splitter = new ListSplitter(messages);
while (splitter.hasNext()) {
try {
List<Message> listItem = splitter.next();
producer.send(listItem);
} catch (Exception e) {
e.printStackTrace();
//处理error
}
}
在大多数情况下,TAG是一个简单而有用的设计,其可以来选择您想要的消息。例如:
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("CID_EXAMPLE");
consumer.subscribe("TOPIC", "TAGA || TAGB || TAGC");
消费者将接收包含TAGA或TAGB或TAGC的消息。但是限制是一个消息只能有一个标签,这对于复杂的场景可能不起作用。在这种情况下,可以使用SQL表达式筛选消息。SQL特性可以通过发送消息时的属性来进行计算。在RocketMQ定义的语法下,可以实现一些简单的逻辑。下面是一个例子:
------------
| message |
|----------| a > 5 AND b = 'abc'
| a = 10 | --------------------> Gotten
| b = 'abc'|
| c = true |
------------
------------
| message |
|----------| a > 5 AND b = 'abc'
| a = 1 | --------------------> Missed
| b = 'abc'|
| c = true |
------------
RocketMQ只定义了一些基本语法来支持这个特性。你也可以很容易地扩展它。
常量支持类型为:
只有使用push模式的消费者才能用使用SQL92标准的sql语句,接口如下:
public void subscribe(finalString topic, final MessageSelector messageSelector)
public class TagProducer {
public static void main(String[] args) throws Exception {
//1.创建消费者Consumer,指定消费者组名group1
DefaultMQProducer producer = new DefaultMQProducer("group1");
//2.指定Nameserver地址,集群多台用分号隔开
producer.setNamesrvAddr("192.168.79.203:9876;192.168.79.204:9876");
//3.启动producer
producer.start();
String tags[] = {"TagA","TagB","TagC"};
for (int i = 0; i < 3; i++) {
//4.创建消息对象,指定主题Topic、Tag和消息体
/**
* 参数1:消息主题
* 参数2 tag
* 参数3:消息内存
*/
Message msg = new Message("TagTopic" , tags[i], ("Hello RocketMQ " + i).getBytes());
//5.发送消息,通过sendResult返回消息是否成功送达
SendResult sendResult = producer.send(msg);
System.out.println("发送结果:" + sendResult);
}
//6.关闭生产者producer, 如果不再发送消息,关闭Producer实例。
producer.shutdown();
}
}
public class TagConsumer {
public static void main(String[] args) throws MQClientException {
//1.创建消费者Consumer,制定消费者组名
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
//2.指定Nameserver地址
consumer.setNamesrvAddr("192.168.79.203:9876;192.168.79.204:9876");
//3.订阅主题Topic和Tag * 表示接收该topic所有tag消息; TagA || TagB 表示接收TagA和TagB的消息
consumer.subscribe("TagTopic", "TagA || TagB");
//4.设置回调函数,处理消息
consumer.registerMessageListener(new MessageListenerConcurrently(){
/**
* 接收消息内容的方法
* @param msgs
* @param context 消费者并发消费环境
* @return
*/
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
for (MessageExt msg : msgs) {
String tags = msg.getTags();
System.out.println("消息tag:"+tags);
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
//5.启动消费者consumer
consumer.start();
System.out.println("消费者启动成功");
}
}
发送消息时,你能通过putUserProperty
来设置消息的属性
public class SqlProducer {
public static void main(String[] args) throws Exception {
//1.创建消费者Consumer,指定消费者组名group1
DefaultMQProducer producer = new DefaultMQProducer("group1");
//2.指定Nameserver地址,集群多台用分号隔开
producer.setNamesrvAddr("192.168.79.203:9876;192.168.79.204:9876");
//3.启动producer
producer.start();
String tags[] = {"TagA","TagB","TagC"};
for (int i = 0; i < 3; i++) {
//4.创建消息对象,指定主题Topic、Tag和消息体
/**
* 参数1:消息主题
* 参数2 tag
* 参数3:消息内存
*/
Message msg = new Message("SqlFilterTopic" , tags[i], ("Hello RocketMQ " + i).getBytes());
// 设置一些属性
msg.putUserProperty("a", String.valueOf(i));
//5.发送消息,通过sendResult返回消息是否成功送达
SendResult sendResult = producer.send(msg);
System.out.println("发送结果:" + sendResult);
}
//6.关闭生产者producer, 如果不再发送消息,关闭Producer实例。
producer.shutdown();
}
}
用MessageSelector.bySql来使用sql筛选消息
public class SqlConsumer {
public static void main(String[] args) throws MQClientException {
//1.创建消费者Consumer,制定消费者组名
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
//2.指定Nameserver地址
consumer.setNamesrvAddr("192.168.79.203:9876;192.168.79.204:9876");
//3.订阅主题Topic,只有订阅的消息有这个属性a, a >=0 and a <= 3
//这里根据sql进行过滤和tag没有关系
consumer.subscribe("SqlFilterTopic", MessageSelector.bySql("a between 0 and 3"));
//4.设置回调函数,处理消息
consumer.registerMessageListener(new MessageListenerConcurrently(){
/**
* 接收消息内容的方法
* @param msgs
* @param context 消费者并发消费环境
* @return
*/
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
for (MessageExt msg : msgs) {
String tags = msg.getTags();
System.out.println("消息tag:"+tags);
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
//5.启动消费者consumer
consumer.start();
System.out.println("消费者启动成功");
}
}
测试结果
消息tag:TagA
消息tag:TagB
消息tag:TagC
注意,如果要支持sql过滤需要在broker配置文件中开启sql过滤支持 #开启sql过滤支持 enablePropertyFilter=true
上图说明了事务消息的大致方案,其中分为两个流程:正常事务消息的发送及提交、事务消息的补偿流程。
####1)事务消息发送及提交
(1) 发送消息(half消息)。
(2) 服务端响应消息写入结果。
(3) 根据发送结果执行本地事务(如果写入失败,此时half消息对业务不可见,本地逻辑不执行)。
(4) 根据本地事务状态执行Commit或者Rollback(Commit操作生成消息索引,消息对消费者可见)
(1) 对没有Commit/Rollback的事务消息(pending状态的消息),从服务端发起一次“回查”
(2) Producer收到回查消息,检查回查消息对应的本地事务的状态
(3) 根据本地事务状态,重新Commit或者Rollback
其中,补偿阶段用于解决消息Commit或者Rollback发生超时或者失败的情况。
事务消息共有三种状态,提交状态、回滚状态、中间状态:
使用 TransactionMQProducer
类创建生产者,并指定唯一的 ProducerGroup
,就可以设置自定义线程池来处理这些检查请求。执行本地事务后、需要根据执行结果对消息队列进行回复。回传的事务状态在请参考前一节。
public class TransactionProducer {
public static void main(String[] args) throws Exception {
//1.创建消息生产者
TransactionMQProducer producer = new TransactionMQProducer("group6");
//2.设置NameServer的地址
producer.setNamesrvAddr("192.168.79.203:9876;192.168.79.204:9876");
//3.创建事务监听器
TransactionListener transactionListener = new TransactionListener(){
//执行本地事务
@Override
public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
System.out.println("执行本地事务");
if (StringUtils.equals("TagA", msg.getTags())) {
return LocalTransactionState.COMMIT_MESSAGE;
} else if (StringUtils.equals("TagB", msg.getTags())) {
return LocalTransactionState.ROLLBACK_MESSAGE;
} else {
return LocalTransactionState.UNKNOW;
}
}
//如果存在消息状态不明的消息(LocalTransactionState.UNKNOW),MQ会检查消息的本地事务执行结果
@Override
public LocalTransactionState checkLocalTransaction(MessageExt msg) {
System.out.println("MQ检查消息Tag【"+msg.getTags()+"】的本地事务执行结果");
return LocalTransactionState.COMMIT_MESSAGE;
}
};
//4.生产者设置监听器
producer.setTransactionListener(transactionListener);
//5.启动消息生产者
producer.start();
String[] tags = new String[]{"TagA", "TagB", "TagC"};
for (int i = 0; i < 3; i++) {
Message msg = new Message("TransactionTopic", tags[i], "KEY" + i,
("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
SendResult sendResult = producer.sendMessageInTransaction(msg, null);
System.out.printf("%s%n", sendResult);
TimeUnit.SECONDS.sleep(1);
}
//producer.shutdown();
}
}
public class TransactionConsumer {
public static void main(String[] args) throws MQClientException {
//1.创建消费者Consumer,制定消费者组名
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
//2.指定Nameserver地址
consumer.setNamesrvAddr("192.168.79.203:9876;192.168.79.204:9876");
//3.订阅主题Topic 只有订阅的消息有这个属性a, a >=0 and a <= 3
consumer.subscribe("TransactionTopic", "*");
//4.设置回调函数,处理消息
consumer.registerMessageListener(new MessageListenerConcurrently(){
/**
* 接收消息内容的方法
* @param msgs
* @param context 消费者并发消费环境
* @return
*/
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
for (MessageExt msg : msgs) {
System.out.println(Thread.currentThread().getName()+"消息内容:"+new String(msg.getBody()));
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
//5.启动消费者consumer
consumer.start();
System.out.println("消费者启动成功");
}
}
当发送半消息成功时,我们使用 executeLocalTransaction
方法来执行本地事务。它返回前一节中提到的三个事务状态之一。checkLocalTranscation
方法用于检查本地事务状态,并回应消息队列的检查请求。它也是返回前一节中提到的三个事务状态之一。
public class TransactionListenerImpl implements TransactionListener {
@Override
public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
System.out.println("执行本地事务");
if (StringUtils.equals("TagA", msg.getTags())) {
return LocalTransactionState.COMMIT_MESSAGE;
} else if (StringUtils.equals("TagB", msg.getTags())) {
return LocalTransactionState.ROLLBACK_MESSAGE;
} else {
return LocalTransactionState.UNKNOW;
}
}
@Override
public LocalTransactionState checkLocalTransaction(MessageExt msg) {
System.out.println("MQ检查消息Tag【"+msg.getTags()+"】的本地事务执行结果");
return LocalTransactionState.COMMIT_MESSAGE;
}
}
transactionCheckMax
参数来修改此限制。如果已经检查某条消息超过 N 次的话( N = transactionCheckMax
) 则 Broker 将丢弃此消息,并在默认情况下同时打印错误日志。用户可以通过重写 AbstractTransactionCheckListener
类来修改这个行为。transactionMsgTimeout
参数。