1 基本样例

在基本样例中我们提供如下的功能场景:

  • 使用RocketMQ发送三种类型的消息:同步消息、异步消息和单向消息。其中前两种消息是可靠的,因为会有发送是否成功的应答。
  • 使用RocketMQ来消费接收到的消息。

1.1 加入依赖:

  1. // maven:
  2. <dependency>
  3. <groupId>org.apache.rocketmq</groupId>
  4. <artifactId>rocketmq-client</artifactId>
  5. <version>4.3.0</version>
  6. </dependency>
  7. // gradle
  8. compile 'org.apache.rocketmq:rocketmq-client:4.3.0'

1.2 消息发送

1、Producer端发送同步消息

这种可靠性同步地发送方式使用的比较广泛,比如:重要的消息通知,短信通知。

  1. public class SyncProducer {
  2. public static void main(String[] args) throws Exception {
  3. // 实例化消息生产者Producer
  4. DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
  5. // 设置NameServer的地址
  6. producer.setNamesrvAddr("localhost:9876");
  7. // 启动Producer实例
  8. producer.start();
  9. for (int i = 0; i < 100; i++) {
  10. // 创建消息,并指定Topic,Tag和消息体
  11. Message msg = new Message("TopicTest" /* Topic */,
  12. "TagA" /* Tag */,
  13. ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
  14. );
  15. // 发送消息到一个Broker
  16. SendResult sendResult = producer.send(msg);
  17. // 通过sendResult返回消息是否成功送达
  18. System.out.printf("%s%n", sendResult);
  19. }
  20. // 如果不再发送消息,关闭Producer实例。
  21. producer.shutdown();
  22. }
  23. }

2、发送异步消息

异步消息通常用在对响应时间敏感的业务场景,即发送端不能容忍长时间地等待Broker的响应。

  1. public class AsyncProducer {
  2. public static void main(String[] args) throws Exception {
  3. // 实例化消息生产者Producer
  4. DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
  5. // 设置NameServer的地址
  6. producer.setNamesrvAddr("localhost:9876");
  7. // 启动Producer实例
  8. producer.start();
  9. producer.setRetryTimesWhenSendAsyncFailed(0);
  10. int messageCount = 100;
  11. // 根据消息数量实例化倒计时计算器
  12. final CountDownLatch2 countDownLatch = new CountDownLatch2(messageCount);
  13. for (int i = 0; i < messageCount; i++) {
  14. final int index = i;
  15. // 创建消息,并指定Topic,Tag和消息体
  16. Message msg = new Message("TopicTest",
  17. "TagA",
  18. "OrderID188",
  19. "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
  20. // SendCallback接收异步返回结果的回调
  21. producer.send(msg, new SendCallback() {
  22. @Override
  23. public void onSuccess(SendResult sendResult) {
  24. System.out.printf("%-10d OK %s %n", index,
  25. sendResult.getMsgId());
  26. }
  27. @Override
  28. public void onException(Throwable e) {
  29. System.out.printf("%-10d Exception %s %n", index, e);
  30. e.printStackTrace();
  31. }
  32. });
  33. }
  34. // 等待5s
  35. countDownLatch.await(5, TimeUnit.SECONDS);
  36. // 如果不再发送消息,关闭Producer实例。
  37. producer.shutdown();
  38. }
  39. }

3、单向发送消息

这种方式主要用在不特别关心发送结果的场景,例如日志发送。

  1. public class OnewayProducer {
  2. public static void main(String[] args) throws Exception{
  3. // 实例化消息生产者Producer
  4. DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
  5. // 设置NameServer的地址
  6. producer.setNamesrvAddr("localhost:9876");
  7. // 启动Producer实例
  8. producer.start();
  9. for (int i = 0; i < 100; i++) {
  10. // 创建消息,并指定Topic,Tag和消息体
  11. Message msg = new Message("TopicTest" /* Topic */,
  12. "TagA" /* Tag */,
  13. ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
  14. );
  15. // 发送单向消息,没有任何返回结果
  16. producer.sendOneway(msg);
  17. }
  18. // 如果不再发送消息,关闭Producer实例。
  19. producer.shutdown();
  20. }
  21. }

1.3 消费消息

  1. public class Consumer {
  2. public static void main(String[] args) throws InterruptedException, MQClientException {
  3. // 实例化消费者
  4. DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name");
  5. // 设置NameServer的地址
  6. consumer.setNamesrvAddr("localhost:9876");
  7. // 订阅一个或者多个Topic,以及Tag来过滤需要消费的消息
  8. consumer.subscribe("TopicTest", "*");
  9. // 注册回调实现类来处理从broker拉取回来的消息
  10. consumer.registerMessageListener(new MessageListenerConcurrently() {
  11. @Override
  12. public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
  13. System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
  14. // 标记该消息已经被成功消费
  15. return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
  16. }
  17. });
  18. // 启动消费者实例
  19. consumer.start();
  20. System.out.printf("Consumer Started.%n");
  21. }
  22. }

2 顺序消息样例

消息有序指的是可以按照消息的发送顺序来消费(FIFO)。RocketMQ可以严格的保证消息有序,可以分为分区有序或者全局有序。

顺序消费的原理解析,在默认的情况下消息发送会采取Round Robin轮询方式把消息发送到不同的queue(分区队列);而消费消息的时候从多个queue上拉取消息,这种情况发送和消费是不能保证顺序。但是如果控制发送的顺序消息只依次发送到同一个queue中,消费的时候只从这个queue上依次拉取,则就保证了顺序。当发送和消费参与的queue只有一个,则是全局有序;如果多个queue参与,则为分区有序,即相对每个queue,消息都是有序的。

下面用订单进行分区有序的示例。一个订单的顺序流程是:创建、付款、推送、完成。订单号相同的消息会被先后发送到同一个队列中,消费时,同一个OrderId获取到的肯定是同一个队列。

2.1 顺序消息生产

  1. package org.apache.rocketmq.example.order2;
  2. import org.apache.rocketmq.client.producer.DefaultMQProducer;
  3. import org.apache.rocketmq.client.producer.MessageQueueSelector;
  4. import org.apache.rocketmq.client.producer.SendResult;
  5. import org.apache.rocketmq.common.message.Message;
  6. import org.apache.rocketmq.common.message.MessageQueue;
  7. import java.text.SimpleDateFormat;
  8. import java.util.ArrayList;
  9. import java.util.Date;
  10. import java.util.List;
  11. /**
  12. * Producer,发送顺序消息
  13. */
  14. public class Producer {
  15. public static void main(String[] args) throws Exception {
  16. DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
  17. producer.setNamesrvAddr("127.0.0.1:9876");
  18. producer.start();
  19. String[] tags = new String[]{"TagA", "TagC", "TagD"};
  20. // 订单列表
  21. List<OrderStep> orderList = new Producer().buildOrders();
  22. Date date = new Date();
  23. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  24. String dateStr = sdf.format(date);
  25. for (int i = 0; i < 10; i++) {
  26. // 加个时间前缀
  27. String body = dateStr + " Hello RocketMQ " + orderList.get(i);
  28. Message msg = new Message("TopicTest", tags[i % tags.length], "KEY" + i, body.getBytes());
  29. SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
  30. @Override
  31. public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
  32. Long id = (Long) arg; //根据订单id选择发送queue
  33. long index = id % mqs.size();
  34. return mqs.get((int) index);
  35. }
  36. }, orderList.get(i).getOrderId());//订单id
  37. System.out.println(String.format("SendResult status:%s, queueId:%d, body:%s",
  38. sendResult.getSendStatus(),
  39. sendResult.getMessageQueue().getQueueId(),
  40. body));
  41. }
  42. producer.shutdown();
  43. }
  44. /**
  45. * 订单的步骤
  46. */
  47. private static class OrderStep {
  48. private long orderId;
  49. private String desc;
  50. public long getOrderId() {
  51. return orderId;
  52. }
  53. public void setOrderId(long orderId) {
  54. this.orderId = orderId;
  55. }
  56. public String getDesc() {
  57. return desc;
  58. }
  59. public void setDesc(String desc) {
  60. this.desc = desc;
  61. }
  62. @Override
  63. public String toString() {
  64. return "OrderStep{" +
  65. "orderId=" + orderId +
  66. ", desc='" + desc + '\'' +
  67. '}';
  68. }
  69. }
  70. /**
  71. * 生成模拟订单数据
  72. */
  73. private List<OrderStep> buildOrders() {
  74. List<OrderStep> orderList = new ArrayList<OrderStep>();
  75. OrderStep orderDemo = new OrderStep();
  76. orderDemo.setOrderId(15103111039L);
  77. orderDemo.setDesc("创建");
  78. orderList.add(orderDemo);
  79. orderDemo = new OrderStep();
  80. orderDemo.setOrderId(15103111065L);
  81. orderDemo.setDesc("创建");
  82. orderList.add(orderDemo);
  83. orderDemo = new OrderStep();
  84. orderDemo.setOrderId(15103111039L);
  85. orderDemo.setDesc("付款");
  86. orderList.add(orderDemo);
  87. orderDemo = new OrderStep();
  88. orderDemo.setOrderId(15103117235L);
  89. orderDemo.setDesc("创建");
  90. orderList.add(orderDemo);
  91. orderDemo = new OrderStep();
  92. orderDemo.setOrderId(15103111065L);
  93. orderDemo.setDesc("付款");
  94. orderList.add(orderDemo);
  95. orderDemo = new OrderStep();
  96. orderDemo.setOrderId(15103117235L);
  97. orderDemo.setDesc("付款");
  98. orderList.add(orderDemo);
  99. orderDemo = new OrderStep();
  100. orderDemo.setOrderId(15103111065L);
  101. orderDemo.setDesc("完成");
  102. orderList.add(orderDemo);
  103. orderDemo = new OrderStep();
  104. orderDemo.setOrderId(15103111039L);
  105. orderDemo.setDesc("推送");
  106. orderList.add(orderDemo);
  107. orderDemo = new OrderStep();
  108. orderDemo.setOrderId(15103117235L);
  109. orderDemo.setDesc("完成");
  110. orderList.add(orderDemo);
  111. orderDemo = new OrderStep();
  112. orderDemo.setOrderId(15103111039L);
  113. orderDemo.setDesc("完成");
  114. orderList.add(orderDemo);
  115. return orderList;
  116. }
  117. }

2.2 顺序消费消息

  1. import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
  2. import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
  3. import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
  4. import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
  5. import org.apache.rocketmq.common.message.MessageExt;
  6. import java.util.List;
  7. package org.apache.rocketmq.example.order2;
  8. import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
  9. import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
  10. import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
  11. import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
  12. import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
  13. import org.apache.rocketmq.common.message.MessageExt;
  14. import java.util.List;
  15. import java.util.Random;
  16. import java.util.concurrent.TimeUnit;
  17. /**
  18. * 顺序消息消费,带事务方式(应用可控制Offset什么时候提交)
  19. */
  20. public class ConsumerInOrder {
  21. public static void main(String[] args) throws Exception {
  22. DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name_3");
  23. consumer.setNamesrvAddr("127.0.0.1:9876");
  24. /**
  25. * 设置Consumer第一次启动是从队列头部开始消费还是队列尾部开始消费<br>
  26. * 如果非第一次启动,那么按照上次消费的位置继续消费
  27. */
  28. consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
  29. consumer.subscribe("TopicTest", "TagA || TagC || TagD");
  30. consumer.registerMessageListener(new MessageListenerOrderly() {
  31. Random random = new Random();
  32. @Override
  33. public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
  34. context.setAutoCommit(true);
  35. for (MessageExt msg : msgs) {
  36. // 可以看到每个queue有唯一的consume线程来消费, 订单对每个queue(分区)有序
  37. System.out.println("consumeThread=" + Thread.currentThread().getName() + "queueId=" + msg.getQueueId() + ", content:" + new String(msg.getBody()));
  38. }
  39. try {
  40. //模拟业务逻辑处理中...
  41. TimeUnit.SECONDS.sleep(random.nextInt(10));
  42. } catch (Exception e) {
  43. e.printStackTrace();
  44. }
  45. return ConsumeOrderlyStatus.SUCCESS;
  46. }
  47. });
  48. consumer.start();
  49. System.out.println("Consumer Started.");
  50. }
  51. }

3 延时消息样例

3.1 启动消费者等待传入订阅消息

  1. import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
  2. import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
  3. import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
  4. import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
  5. import org.apache.rocketmq.common.message.MessageExt;
  6. import java.util.List;
  7. public class ScheduledMessageConsumer {
  8. public static void main(String[] args) throws Exception {
  9. // 实例化消费者
  10. DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("ExampleConsumer");
  11. // 订阅Topics
  12. consumer.subscribe("TestTopic", "*");
  13. // 注册消息监听者
  14. consumer.registerMessageListener(new MessageListenerConcurrently() {
  15. @Override
  16. public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> messages, ConsumeConcurrentlyContext context) {
  17. for (MessageExt message : messages) {
  18. // Print approximate delay time period
  19. System.out.println("Receive message[msgId=" + message.getMsgId() + "] " + (System.currentTimeMillis() - message.getStoreTimestamp()) + "ms later");
  20. }
  21. return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
  22. }
  23. });
  24. // 启动消费者
  25. consumer.start();
  26. }
  27. }

3.2 发送延时消息

  1. import org.apache.rocketmq.client.producer.DefaultMQProducer;
  2. import org.apache.rocketmq.common.message.Message;
  3. public class ScheduledMessageProducer {
  4. public static void main(String[] args) throws Exception {
  5. // 实例化一个生产者来产生延时消息
  6. DefaultMQProducer producer = new DefaultMQProducer("ExampleProducerGroup");
  7. // 启动生产者
  8. producer.start();
  9. int totalMessagesToSend = 100;
  10. for (int i = 0; i < totalMessagesToSend; i++) {
  11. Message message = new Message("TestTopic", ("Hello scheduled message " + i).getBytes());
  12. // 设置延时等级3,这个消息将在10s之后发送(现在只支持固定的几个时间,详看delayTimeLevel)
  13. message.setDelayTimeLevel(3);
  14. // 发送消息
  15. producer.send(message);
  16. }
  17. // 关闭生产者
  18. producer.shutdown();
  19. }
  20. }

3.3 验证

您将会看到消息的消费比存储时间晚10秒。

3.4 延时消息的使用场景

比如电商里,提交了一个订单就可以发送一个延时消息,1h后去检查这个订单的状态,如果还是未付款就取消订单释放库存。

3.5 延时消息的使用限制

  1. // org/apache/rocketmq/store/config/MessageStoreConfig.java
  2. 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
消息消费失败会进入延时消息队列,消息发送时间与设置的延时等级和重试次数有关,详见代码SendMessageProcessor.java

4 批量消息样例

批量发送消息能显著提高传递小消息的性能。限制是这些批量消息应该有相同的topic,相同的waitStoreMsgOK,而且不能是延时消息。此外,这一批消息的总大小不应超过4MB。

4.1 发送批量消息

如果您每次只发送不超过4MB的消息,则很容易使用批处理,样例如下:

  1. String topic = "BatchTest";
  2. List<Message> messages = new ArrayList<>();
  3. messages.add(new Message(topic, "TagA", "OrderID001", "Hello world 0".getBytes()));
  4. messages.add(new Message(topic, "TagA", "OrderID002", "Hello world 1".getBytes()));
  5. messages.add(new Message(topic, "TagA", "OrderID003", "Hello world 2".getBytes()));
  6. try {
  7. producer.send(messages);
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. //处理error
  11. }

4.2 消息列表分割

复杂度只有当你发送大批量时才会增长,你可能不确定它是否超过了大小限制(4MB)。这时候你最好把你的消息列表分割一下:

  1. public class ListSplitter implements Iterator<List<Message>> {
  2. private final int SIZE_LIMIT = 1024 * 1024 * 4;
  3. private final List<Message> messages;
  4. private int currIndex;
  5. public ListSplitter(List<Message> messages) {
  6. this.messages = messages;
  7. }
  8. @Override public boolean hasNext() {
  9. return currIndex < messages.size();
  10. }
  11. @Override public List<Message> next() {
  12. int startIndex = getStartIndex();
  13. int nextIndex = startIndex;
  14. int totalSize = 0;
  15. for (; nextIndex < messages.size(); nextIndex++) {
  16. Message message = messages.get(nextIndex);
  17. int tmpSize = calcMessageSize(message);
  18. if (tmpSize + totalSize > SIZE_LIMIT) {
  19. break;
  20. } else {
  21. totalSize += tmpSize;
  22. }
  23. }
  24. List<Message> subList = messages.subList(startIndex, nextIndex);
  25. currIndex = nextIndex;
  26. return subList;
  27. }
  28. private int getStartIndex() {
  29. Message currMessage = messages.get(currIndex);
  30. int tmpSize = calcMessageSize(currMessage);
  31. while(tmpSize > SIZE_LIMIT) {
  32. currIndex += 1;
  33. Message message = messages.get(curIndex);
  34. tmpSize = calcMessageSize(message);
  35. }
  36. return currIndex;
  37. }
  38. private int calcMessageSize(Message message) {
  39. int tmpSize = message.getTopic().length() + message.getBody().length();
  40. Map<String, String> properties = message.getProperties();
  41. for (Map.Entry<String, String> entry : properties.entrySet()) {
  42. tmpSize += entry.getKey().length() + entry.getValue().length();
  43. }
  44. tmpSize = tmpSize + 20; // 增加⽇日志的开销20字节
  45. return tmpSize;
  46. }
  47. }
  48. //把大的消息分裂成若干个小的消息
  49. ListSplitter splitter = new ListSplitter(messages);
  50. while (splitter.hasNext()) {
  51. try {
  52. List<Message> listItem = splitter.next();
  53. producer.send(listItem);
  54. } catch (Exception e) {
  55. e.printStackTrace();
  56. //处理error
  57. }
  58. }

5 过滤消息样例

在大多数情况下,TAG是一个简单而有用的设计,其可以来选择您想要的消息。例如:

  1. DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("CID_EXAMPLE");
  2. consumer.subscribe("TOPIC", "TAGA || TAGB || TAGC");

消费者将接收包含TAGA或TAGB或TAGC的消息。但是限制是一个消息只能有一个标签,这对于复杂的场景可能不起作用。在这种情况下,可以使用SQL表达式筛选消息。SQL特性可以通过发送消息时的属性来进行计算。在RocketMQ定义的语法下,可以实现一些简单的逻辑。下面是一个例子:

  1. ------------
  2. | message |
  3. |----------| a > 5 AND b = 'abc'
  4. | a = 10 | --------------------> Gotten
  5. | b = 'abc'|
  6. | c = true |
  7. ------------
  8. ------------
  9. | message |
  10. |----------| a > 5 AND b = 'abc'
  11. | a = 1 | --------------------> Missed
  12. | b = 'abc'|
  13. | c = true |
  14. ------------

5.1 基本语法

RocketMQ只定义了一些基本语法来支持这个特性。你也可以很容易地扩展它。

  • 数值比较,比如:>,>=,<,<=,BETWEEN,=;
  • 字符比较,比如:=,<>,IN;
  • IS NULL 或者 IS NOT NULL;
  • 逻辑符号 AND,OR,NOT;

常量支持类型为:

  • 数值,比如:123,3.1415;
  • 字符,比如:‘abc’,必须用单引号包裹起来;
  • NULL,特殊的常量
  • 布尔值,TRUEFALSE

只有使用push模式的消费者才能用使用SQL92标准的sql语句,接口如下:

  1. public void subscribe(finalString topic, final MessageSelector messageSelector)

5.2 使用样例

1、生产者样例

发送消息时,你能通过putUserProperty来设置消息的属性

  1. DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
  2. producer.start();
  3. Message msg = new Message("TopicTest",
  4. tag,
  5. ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET)
  6. );
  7. // 设置一些属性
  8. msg.putUserProperty("a", String.valueOf(i));
  9. SendResult sendResult = producer.send(msg);
  10. producer.shutdown();

2、消费者样例

用MessageSelector.bySql来使用sql筛选消息

  1. DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name_4");
  2. // 只有订阅的消息有这个属性a, a >=0 and a <= 3
  3. consumer.subscribe("TopicTest", MessageSelector.bySql("a between 0 and 3");
  4. consumer.registerMessageListener(new MessageListenerConcurrently() {
  5. @Override
  6. public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
  7. return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
  8. }
  9. });
  10. consumer.start();

6 消息事务样例

事务消息共有三种状态,提交状态、回滚状态、中间状态:

  • TransactionStatus.CommitTransaction: 提交事务,它允许消费者消费此消息。
  • TransactionStatus.RollbackTransaction: 回滚事务,它代表该消息将被删除,不允许被消费。
  • TransactionStatus.Unknown: 中间状态,它代表需要检查消息队列来确定状态。

6.1 发送事务消息样例

1、创建事务性生产者

使用 TransactionMQProducer类创建生产者,并指定唯一的 ProducerGroup,就可以设置自定义线程池来处理这些检查请求。执行本地事务后、需要根据执行结果对消息队列进行回复。回传的事务状态在请参考前一节。

  1. import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
  2. import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
  3. import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
  4. import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
  5. import org.apache.rocketmq.common.message.MessageExt;
  6. import java.util.List;
  7. public class TransactionProducer {
  8. public static void main(String[] args) throws MQClientException, InterruptedException {
  9. TransactionListener transactionListener = new TransactionListenerImpl();
  10. TransactionMQProducer producer = new TransactionMQProducer("please_rename_unique_group_name");
  11. ExecutorService executorService = new ThreadPoolExecutor(2, 5, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2000), new ThreadFactory() {
  12. @Override
  13. public Thread newThread(Runnable r) {
  14. Thread thread = new Thread(r);
  15. thread.setName("client-transaction-msg-check-thread");
  16. return thread;
  17. }
  18. });
  19. producer.setExecutorService(executorService);
  20. producer.setTransactionListener(transactionListener);
  21. producer.start();
  22. String[] tags = new String[] {"TagA", "TagB", "TagC", "TagD", "TagE"};
  23. for (int i = 0; i < 10; i++) {
  24. try {
  25. Message msg =
  26. new Message("TopicTest1234", tags[i % tags.length], "KEY" + i,
  27. ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
  28. SendResult sendResult = producer.sendMessageInTransaction(msg, null);
  29. System.out.printf("%s%n", sendResult);
  30. Thread.sleep(10);
  31. } catch (MQClientException | UnsupportedEncodingException e) {
  32. e.printStackTrace();
  33. }
  34. }
  35. for (int i = 0; i < 100000; i++) {
  36. Thread.sleep(1000);
  37. }
  38. producer.shutdown();
  39. }
  40. }

2、实现事务的监听接口

当发送半消息成功时,我们使用 executeLocalTransaction 方法来执行本地事务。它返回前一节中提到的三个事务状态之一。checkLocalTransaction 方法用于检查本地事务状态,并回应消息队列的检查请求。它也是返回前一节中提到的三个事务状态之一。

  1. public class TransactionListenerImpl implements TransactionListener {
  2. private AtomicInteger transactionIndex = new AtomicInteger(0);
  3. private ConcurrentHashMap<String, Integer> localTrans = new ConcurrentHashMap<>();
  4. @Override
  5. public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
  6. int value = transactionIndex.getAndIncrement();
  7. int status = value % 3;
  8. localTrans.put(msg.getTransactionId(), status);
  9. return LocalTransactionState.UNKNOW;
  10. }
  11. @Override
  12. public LocalTransactionState checkLocalTransaction(MessageExt msg) {
  13. Integer status = localTrans.get(msg.getTransactionId());
  14. if (null != status) {
  15. switch (status) {
  16. case 0:
  17. return LocalTransactionState.UNKNOW;
  18. case 1:
  19. return LocalTransactionState.COMMIT_MESSAGE;
  20. case 2:
  21. return LocalTransactionState.ROLLBACK_MESSAGE;
  22. }
  23. }
  24. return LocalTransactionState.COMMIT_MESSAGE;
  25. }
  26. }

6.2 事务消息使用上的限制

  1. 事务消息不支持延时消息和批量消息。
  2. 为了避免单个消息被检查太多次而导致半队列消息累积,我们默认将单个消息的检查次数限制为 15 次,但是用户可以通过 Broker 配置文件的 transactionCheckMax参数来修改此限制。如果已经检查某条消息超过 N 次的话( N = transactionCheckMax ) 则 Broker 将丢弃此消息,并在默认情况下同时打印错误日志。用户可以通过重写 AbstractTransactionalMessageCheckListener 类来修改这个行为。
  3. 事务消息将在 Broker 配置文件中的参数 transactionTimeout 这样的特定时间长度之后被检查。当发送事务消息时,用户还可以通过设置用户属性 CHECK_IMMUNITY_TIME_IN_SECONDS 来改变这个限制,该参数优先于 transactionTimeout 参数。
  4. 事务性消息可能不止一次被检查或消费。
  5. 提交给用户的目标主题消息可能会失败,目前这依日志的记录而定。它的高可用性通过 RocketMQ 本身的高可用性机制来保证,如果希望确保事务消息不丢失、并且事务完整性得到保证,建议使用同步的双重写入机制。
  6. 事务消息的生产者 ID 不能与其他类型消息的生产者 ID 共享。与其他类型的消息不同,事务消息允许反向查询、MQ服务器能通过它们的生产者 ID 查询到消费者。

7 Logappender样例

RocketMQ日志提供log4j、log4j2和logback日志框架作为业务应用,下面是配置样例

7.1 log4j样例

按下面样例使用log4j属性配置

  1. log4j.appender.mq=org.apache.rocketmq.logappender.log4j.RocketmqLog4jAppender
  2. log4j.appender.mq.Tag=yourTag
  3. log4j.appender.mq.Topic=yourLogTopic
  4. log4j.appender.mq.ProducerGroup=yourLogGroup
  5. log4j.appender.mq.NameServerAddress=yourRocketmqNameserverAddress
  6. log4j.appender.mq.layout=org.apache.log4j.PatternLayout
  7. log4j.appender.mq.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-4r [%t] (%F:%L) %-5p - %m%n

按下面样例使用log4j xml配置来使用异步添加日志

  1. <appender name="mqAppender1"class="org.apache.rocketmq.logappender.log4j.RocketmqLog4jAppender">
  2. <param name="Tag" value="yourTag" />
  3. <param name="Topic" value="yourLogTopic" />
  4. <param name="ProducerGroup" value="yourLogGroup" />
  5. <param name="NameServerAddress" value="yourRocketmqNameserverAddress"/>
  6. <layout class="org.apache.log4j.PatternLayout">
  7. <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss}-%p %t %c - %m%n" />
  8. </layout>
  9. </appender>
  10. <appender name="mqAsyncAppender1"class="org.apache.log4j.AsyncAppender">
  11. <param name="BufferSize" value="1024" />
  12. <param name="Blocking" value="false" />
  13. <appender-ref ref="mqAppender1"/>
  14. </appender>

7.2 log4j2样例

用log4j2时,配置如下,如果想要非阻塞,只需要使用异步添加引用即可

  1. <RocketMQ name="rocketmqAppender" producerGroup="yourLogGroup" nameServerAddress="yourRocketmqNameserverAddress"
  2. topic="yourLogTopic" tag="yourTag">
  3. <PatternLayout pattern="%d [%p] hahahah %c %m%n"/>
  4. </RocketMQ>

7.3 logback样例

  1. <appender name="mqAppender1"class="org.apache.rocketmq.logappender.logback.RocketmqLogbackAppender">
  2. <tag>yourTag</tag>
  3. <topic>yourLogTopic</topic>
  4. <producerGroup>yourLogGroup</producerGroup>
  5. <nameServerAddress>yourRocketmqNameserverAddress</nameServerAddress>
  6. <layout>
  7. <pattern>%date %p %t - %m%n</pattern>
  8. </layout>
  9. </appender>
  10. <appender name="mqAsyncAppender1"class="ch.qos.logback.classic.AsyncAppender">
  11. <queueSize>1024</queueSize>
  12. <discardingThreshold>80</discardingThreshold>
  13. <maxFlushTime>2000</maxFlushTime>
  14. <neverBlock>true</neverBlock>
  15. <appender-ref ref="mqAppender1"/>
  16. </appender>

8 OpenMessaging样例

OpenMessaging旨在建立消息和流处理规范,以为金融、电子商务、物联网和大数据领域提供通用框架及工业级指导方案。在分布式异构环境中,设计原则是面向云、简单、灵活和独立于语言。符合这些规范将帮助企业方便的开发跨平台和操作系统的异构消息传递应用程序。提供了openmessaging-api 0.3.0-alpha的部分实现,下面的示例演示如何基于OpenMessaging访问RocketMQ。

8.1 OMSProducer样例

下面的示例演示如何在同步、异步或单向传输中向RocketMQ代理发送消息。

  1. import io.openmessaging.Future;
  2. import io.openmessaging.FutureListener;
  3. import io.openmessaging.Message;
  4. import io.openmessaging.MessagingAccessPoint;
  5. import io.openmessaging.OMS;
  6. import io.openmessaging.producer.Producer;
  7. import io.openmessaging.producer.SendResult;
  8. import java.nio.charset.Charset;
  9. import java.util.concurrent.CountDownLatch;
  10. public class SimpleProducer {
  11. public static void main(String[] args) {
  12. final MessagingAccessPoint messagingAccessPoint =
  13. OMS.getMessagingAccessPoint("oms:rocketmq://localhost:9876/default:default");
  14. final Producer producer = messagingAccessPoint.createProducer();
  15. messagingAccessPoint.startup();
  16. System.out.printf("MessagingAccessPoint startup OK%n");
  17. producer.startup();
  18. System.out.printf("Producer startup OK%n");
  19. {
  20. Message message = producer.createBytesMessage("OMS_HELLO_TOPIC", "OMS_HELLO_BODY".getBytes(Charset.forName("UTF-8")));
  21. SendResult sendResult = producer.send(message);
  22. //final Void aVoid = result.get(3000L);
  23. System.out.printf("Send async message OK, msgId: %s%n", sendResult.messageId());
  24. }
  25. final CountDownLatch countDownLatch = new CountDownLatch(1);
  26. {
  27. final Future<SendResult> result = producer.sendAsync(producer.createBytesMessage("OMS_HELLO_TOPIC", "OMS_HELLO_BODY".getBytes(Charset.forName("UTF-8"))));
  28. result.addListener(new FutureListener<SendResult>() {
  29. @Override
  30. public void operationComplete(Future<SendResult> future) {
  31. if (future.getThrowable() != null) {
  32. System.out.printf("Send async message Failed, error: %s%n", future.getThrowable().getMessage());
  33. } else {
  34. System.out.printf("Send async message OK, msgId: %s%n", future.get().messageId());
  35. }
  36. countDownLatch.countDown();
  37. }
  38. });
  39. }
  40. {
  41. producer.sendOneway(producer.createBytesMessage("OMS_HELLO_TOPIC", "OMS_HELLO_BODY".getBytes(Charset.forName("UTF-8"))));
  42. System.out.printf("Send oneway message OK%n");
  43. }
  44. try {
  45. countDownLatch.await();
  46. Thread.sleep(500); // 等一些时间来发送消息
  47. } catch (InterruptedException ignore) {
  48. }
  49. producer.shutdown();
  50. }
  51. }

8.2 OMSPullConsumer

用OMS PullConsumer 来从指定的队列中拉取消息

  1. import io.openmessaging.Message;
  2. import io.openmessaging.MessagingAccessPoint;
  3. import io.openmessaging.OMS;
  4. import io.openmessaging.OMSBuiltinKeys;
  5. import io.openmessaging.consumer.PullConsumer;
  6. import io.openmessaging.producer.Producer;
  7. import io.openmessaging.producer.SendResult;
  8. public class SimplePullConsumer {
  9. public static void main(String[] args) {
  10. final MessagingAccessPoint messagingAccessPoint =
  11. OMS.getMessagingAccessPoint("oms:rocketmq://localhost:9876/default:default");
  12. messagingAccessPoint.startup();
  13. final Producer producer = messagingAccessPoint.createProducer();
  14. final PullConsumer consumer = messagingAccessPoint.createPullConsumer(
  15. OMS.newKeyValue().put(OMSBuiltinKeys.CONSUMER_ID, "OMS_CONSUMER"));
  16. messagingAccessPoint.startup();
  17. System.out.printf("MessagingAccessPoint startup OK%n");
  18. final String queueName = "TopicTest";
  19. producer.startup();
  20. Message msg = producer.createBytesMessage(queueName, "Hello Open Messaging".getBytes());
  21. SendResult sendResult = producer.send(msg);
  22. System.out.printf("Send Message OK. MsgId: %s%n", sendResult.messageId());
  23. producer.shutdown();
  24. consumer.attachQueue(queueName);
  25. consumer.startup();
  26. System.out.printf("Consumer startup OK%n");
  27. // 运行直到发现一个消息被发送了
  28. boolean stop = false;
  29. while (!stop) {
  30. Message message = consumer.receive();
  31. if (message != null) {
  32. String msgId = message.sysHeaders().getString(Message.BuiltinKeys.MESSAGE_ID);
  33. System.out.printf("Received one message: %s%n", msgId);
  34. consumer.ack(msgId);
  35. if (!stop) {
  36. stop = msgId.equalsIgnoreCase(sendResult.messageId());
  37. }
  38. } else {
  39. System.out.printf("Return without any message%n");
  40. }
  41. }
  42. consumer.shutdown();
  43. messagingAccessPoint.shutdown();
  44. }
  45. }

8.3 OMSPushConsumer

以下示范如何将 OMS PushConsumer 添加到指定的队列,并通过 MessageListener 消费这些消息。

  1. import io.openmessaging.Message;
  2. import io.openmessaging.MessagingAccessPoint;
  3. import io.openmessaging.OMS;
  4. import io.openmessaging.OMSBuiltinKeys;
  5. import io.openmessaging.consumer.MessageListener;
  6. import io.openmessaging.consumer.PushConsumer;
  7. public class SimplePushConsumer {
  8. public static void main(String[] args) {
  9. final MessagingAccessPoint messagingAccessPoint = OMS
  10. .getMessagingAccessPoint("oms:rocketmq://localhost:9876/default:default");
  11. final PushConsumer consumer = messagingAccessPoint.
  12. createPushConsumer(OMS.newKeyValue().put(OMSBuiltinKeys.CONSUMER_ID, "OMS_CONSUMER"));
  13. messagingAccessPoint.startup();
  14. System.out.printf("MessagingAccessPoint startup OK%n");
  15. Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
  16. @Override
  17. public void run() {
  18. consumer.shutdown();
  19. messagingAccessPoint.shutdown();
  20. }
  21. }));
  22. consumer.attachQueue("OMS_HELLO_TOPIC", new MessageListener() {
  23. @Override
  24. public void onReceived(Message message, Context context) {
  25. System.out.printf("Received one message: %s%n", message.sysHeaders().getString(Message.BuiltinKeys.MESSAGE_ID));
  26. context.ack();
  27. }
  28. });
  29. consumer.startup();
  30. System.out.printf("Consumer startup OK%n");
  31. }
  32. }