1 基本样例

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

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

    1.1 加入依赖:

    maven:

    1. <dependency>
    2. <groupId>org.apache.rocketmq</groupId>
    3. <artifactId>rocketmq-client</artifactId>
    4. <version>4.9.1</version>
    5. </dependency>

    gradle:

    1. 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. countDownLatch.countDown();
    25. System.out.printf("%-10d OK %s %n", index,
    26. sendResult.getMsgId());
    27. }
    28. @Override
    29. public void onException(Throwable e) {
    30. countDownLatch.countDown();
    31. System.out.printf("%-10d Exception %s %n", index, e);
    32. e.printStackTrace();
    33. }
    34. });
    35. }
    36. // 等待5s
    37. countDownLatch.await(5, TimeUnit.SECONDS);
    38. // 如果不再发送消息,关闭Producer实例。
    39. producer.shutdown();
    40. }
    41. }

    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 顺序消息生产

    ```java package org.apache.rocketmq.example.order2; import org.apache.rocketmq.client.producer.DefaultMQProducer; import org.apache.rocketmq.client.producer.MessageQueueSelector; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.common.message.Message; import org.apache.rocketmq.common.message.MessageQueue; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /**

  • Producer,发送顺序消息 */ public class Producer { public static void main(String[] args) throws Exception {
    1. DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
    2. producer.setNamesrvAddr("127.0.0.1:9876");
    3. producer.start();
    4. String[] tags = new String[]{"TagA", "TagC", "TagD"};
    5. // 订单列表
    6. List<OrderStep> orderList = new Producer().buildOrders();
    7. Date date = new Date();
    8. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    9. String dateStr = sdf.format(date);
    10. for (int i = 0; i < 10; i++) {
    11. // 加个时间前缀
    12. String body = dateStr + " Hello RocketMQ " + orderList.get(i);
    13. Message msg = new Message("TopicTest", tags[i % tags.length], "KEY" + i, body.getBytes());
    14. SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
    15. @Override
    16. public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
    17. Long id = (Long) arg; //根据订单id选择发送queue
    18. long index = id % mqs.size();
    19. return mqs.get((int) index);
    20. }
    21. }, orderList.get(i).getOrderId());//订单id
    22. System.out.println(String.format("SendResult status:%s, queueId:%d, body:%s",
    23. sendResult.getSendStatus(),
    24. sendResult.getMessageQueue().getQueueId(),
    25. body));
    26. }
    27. producer.shutdown();
    } /**
    • 订单的步骤 */ private static class OrderStep { private long orderId; private String desc; public long getOrderId() {
      1. return orderId;
      } public void setOrderId(long orderId) {
      1. this.orderId = orderId;
      } public String getDesc() {
      1. return desc;
      } public void setDesc(String desc) {
      1. this.desc = desc;
      } @Override public String toString() {
      1. return "OrderStep{" +
      2. "orderId=" + orderId +
      3. ", desc='" + desc + '\'' +
      4. '}';
      } } /**
    • 生成模拟订单数据 */ private List buildOrders() { List orderList = new ArrayList(); 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; } } ```

      2.2 顺序消费消息

      ```java package org.apache.rocketmq.example.order2; import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer; import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext; import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus; import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly; import org.apache.rocketmq.common.consumer.ConsumeFromWhere; import org.apache.rocketmq.common.message.MessageExt; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; /**
  • 顺序消息消费,带事务方式(应用可控制Offset什么时候提交) */ public class ConsumerInOrder { public static void main(String[] args) throws Exception {
    1. DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name_3");
    2. consumer.setNamesrvAddr("127.0.0.1:9876");
    3. /**
    4. * 设置Consumer第一次启动是从队列头部开始消费还是队列尾部开始消费<br>
    5. * 如果非第一次启动,那么按照上次消费的位置继续消费
    6. */
    7. consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
    8. consumer.subscribe("TopicTest", "TagA || TagC || TagD");
    9. consumer.registerMessageListener(new MessageListenerOrderly() {
    10. Random random = new Random();
    11. @Override
    12. public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
    13. context.setAutoCommit(true);
    14. for (MessageExt msg : msgs) {
    15. // 可以看到每个queue有唯一的consume线程来消费, 订单对每个queue(分区)有序
    16. System.out.println("consumeThread=" + Thread.currentThread().getName() + "queueId=" + msg.getQueueId() + ", content:" + new String(msg.getBody()));
    17. }
    18. try {
    19. //模拟业务逻辑处理中...
    20. TimeUnit.SECONDS.sleep(random.nextInt(10));
    21. } catch (Exception e) {
    22. e.printStackTrace();
    23. }
    24. return ConsumeOrderlyStatus.SUCCESS;
    25. }
    26. });
    27. consumer.start();
    28. System.out.println("Consumer Started.");
    } }
    1. <a name="1669b165"></a>
    2. ## 3 延时消息样例
    3. <a name="e73a9f22"></a>
    4. ### 3.1 启动消费者等待传入订阅消息
    5. ```java
    6. import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
    7. import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
    8. import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
    9. import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
    10. import org.apache.rocketmq.common.message.MessageExt;
    11. import java.util.List;
    12. public class ScheduledMessageConsumer {
    13. public static void main(String[] args) throws Exception {
    14. // 实例化消费者
    15. DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("ExampleConsumer");
    16. // 订阅Topics
    17. consumer.subscribe("TestTopic", "*");
    18. // 注册消息监听者
    19. consumer.registerMessageListener(new MessageListenerConcurrently() {
    20. @Override
    21. public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> messages, ConsumeConcurrentlyContext context) {
    22. for (MessageExt message : messages) {
    23. // Print approximate delay time period
    24. System.out.println("Receive message[msgId=" + message.getMsgId() + "] " + (System.currentTimeMillis() - message.getBornTimestamp()) + "ms later");
    25. }
    26. return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    27. }
    28. });
    29. // 启动消费者
    30. consumer.start();
    31. }
    32. }

    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定义的语法下,可以实现一些简单的逻辑。下面是一个例子: ```

| 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 |

  1. <a name="c7226666"></a>
  2. ### 5.1 基本语法
  3. RocketMQ只定义了一些基本语法来支持这个特性。你也可以很容易地扩展它。
  4. - 数值比较,比如:**>,>=,<,<=,BETWEEN,=;**
  5. - 字符比较,比如:**=,<>,IN;**
  6. - **IS NULL** 或者 **IS NOT NULL;**
  7. - 逻辑符号 **AND,OR,NOT;**
  8. 常量支持类型为:
  9. - 数值,比如:**123,3.1415;**
  10. - 字符,比如:**'abc',必须用单引号包裹起来;**
  11. - **NULL**,特殊的常量
  12. - 布尔值,**TRUE** 或 **FALSE**
  13. 只有使用push模式的消费者才能用使用SQL92标准的sql语句,接口如下:

public void subscribe(finalString topic, final MessageSelector messageSelector)

  1. <a name="05649805"></a>
  2. ### 5.2 使用样例
  3. <a name="0330d1f3"></a>
  4. #### 1、生产者样例
  5. 发送消息时,你能通过`putUserProperty`来设置消息的属性
  6. ```java
  7. DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
  8. producer.start();
  9. Message msg = new Message("TopicTest",
  10. tag,
  11. ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET)
  12. );
  13. // 设置一些属性
  14. msg.putUserProperty("a", String.valueOf(i));
  15. SendResult sendResult = producer.send(msg);
  16. 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. }