当前位置:   article > 正文

RocketMQ 消息结构和消息类型_rocketmq输出格式

rocketmq输出格式

发送消息的一方称为生产者,负责生产消息,一般由业务系统负责生产消息。一个消息生产者会把业务应用系统里产生的消息发送到 broker 服务器。RocketMQ 提供多种发送方式,同步发送、异步发送、顺序发送、单向发送。同步和异步方式均需要 Broker 返回确认信息,单向发送不需要。

Producer 发送同一类消息且发送逻辑一致,这类消息被称为 Producer group。如果发送的是事务消息且原始生产者在发送之后崩溃,则 Broker 服务器会联系同一生产者组的其他生产者实例以提交或回溯消费。

它在整个 RocketMQ 的生产和消费体系中扮演的角色如下图所示:

生产者: 一个逻辑概念,在使用生产者实例的时候需要指定一个组名。一个生产者组可以生产多个 Topic 消息。

生产者实例:一个生产者组部署了多个进程,每个进程都可以成为一个生产者实例。

Topic:主题名字,表示一类消息的集合,一个 Topic 由若干 Queue 组成。每个主题包含若干条消息,每条消息只能属于一个主题,是 RocketMQ 进行消息订阅的基本单位。

RocketMQ 客户端中的生产者有两个独立的生产者实现类:

org.apache.rocketmq.client.producer.DefaultMQProducer
org.apache.rocketmq.client.producer.TransactionMQProducer

其中 DefaultMQProducer 主要负责生产普通消息、顺序消息、单向消息、批量消息和延迟消息,TransactionMQProducer 主要负责生产事务消息。

消息结构和消息类型

RocketMQ 消息定义相关的代码位于 org.apache.rocketmq.common.message.Message 下,Producer 发送的消息定义为 Message 类,其基本字段为:

  1. public class Message implements Serializable {
  2. private static final long serialVersionUID = 8445773977080406428L;
  3. private String topic;
  4. private int flag;
  5. private Map<String, String> properties;
  6. private byte[] body;
  7. private String transactionId;
  8. public Message() {
  9. }
  10. public Message(String topic, byte[] body) {
  11. this(topic, "", "", 0, body, true);
  12. }
  13. public String getTopic() {
  14. return topic;
  15. }
  16. public void setTopic(String topic) {
  17. this.topic = topic;
  18. }
  19. public int getFlag() {
  20. return flag;
  21. }
  22. public void setFlag(int flag) {
  23. this.flag = flag;
  24. }
  25. public byte[] getBody() {
  26. return body;
  27. }
  28. public void setBody(byte[] body) {
  29. this.body = body;
  30. }
  31. public Map<String, String> getProperties() {
  32. return properties;
  33. }
  34. void setProperties(Map<String, String> properties) {
  35. this.properties = properties;
  36. }
  37. public String getTransactionId() {
  38. return transactionId;
  39. }
  40. public void setTransactionId(String transactionId) {
  41. this.transactionId = transactionId;
  42. }
  43. @Override
  44. public String toString() {
  45. return "Message{" +
  46. "topic='" + topic + '\'' +
  47. ", flag=" + flag +
  48. ", properties=" + properties +
  49. ", body=" + Arrays.toString(body) +
  50. ", transactionId='" + transactionId + '\'' +
  51. '}';
  52. }
  53. }

各个字段的含义为:

topic:主题名字,可以通过 RocketMQ COnsole 创建。Message 都有 Topic 这一属性,Producer 发送指定 Topic 的消息,Consumer 订阅 Topic 下的消息。通过 Topic 字段,Producer 会获取消息投递的路由信息,决定发送给哪个 Broker。

flag:网络通信层标记,目前用到的地方很少。

properties:消息扩展信息,该字段是 HashMap 类型的,用来存储 Message 的其余各项参数,比如 tag、key 等关键的消息属性。RocketMQ 预定义了一组内置属性,除了内置属性之外,还可以设置任意自定义属性。当然属性的数量也是有限的,消息序列化之后的大小不能超过预设的最大消息大小。系统内置属性定义于 org.apache.rocketmq.common.message.MessageConst,内置属性有:

  1. public class MessageConst {
  2. public static final String PROPERTY_KEYS = "KEYS";
  3. public static final String PROPERTY_TAGS = "TAGS";
  4. public static final String PROPERTY_WAIT_STORE_MSG_OK = "WAIT";
  5. public static final String PROPERTY_DELAY_TIME_LEVEL = "DELAY";
  6. public static final String PROPERTY_RETRY_TOPIC = "RETRY_TOPIC";
  7. public static final String PROPERTY_REAL_TOPIC = "REAL_TOPIC";
  8. public static final String PROPERTY_REAL_QUEUE_ID = "REAL_QID";
  9. public static final String PROPERTY_TRANSACTION_PREPARED = "TRAN_MSG";
  10. public static final String PROPERTY_PRODUCER_GROUP = "PGROUP";
  11. public static final String PROPERTY_MIN_OFFSET = "MIN_OFFSET";
  12. public static final String PROPERTY_MAX_OFFSET = "MAX_OFFSET";
  13. public static final String PROPERTY_BUYER_ID = "BUYER_ID";
  14. public static final String PROPERTY_ORIGIN_MESSAGE_ID = "ORIGIN_MESSAGE_ID";
  15. public static final String PROPERTY_TRANSFER_FLAG = "TRANSFER_FLAG";
  16. public static final String PROPERTY_CORRECTION_FLAG = "CORRECTION_FLAG";
  17. public static final String PROPERTY_MQ2_FLAG = "MQ2_FLAG";
  18. public static final String PROPERTY_RECONSUME_TIME = "RECONSUME_TIME";
  19. public static final String PROPERTY_MSG_REGION = "MSG_REGION";
  20. public static final String PROPERTY_TRACE_SWITCH = "TRACE_ON";
  21. public static final String PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX = "UNIQ_KEY";
  22. public static final String PROPERTY_MAX_RECONSUME_TIMES = "MAX_RECONSUME_TIMES";
  23. public static final String PROPERTY_CONSUME_START_TIMESTAMP = "CONSUME_START_TIME";
  24. public static final String PROPERTY_TRANSACTION_PREPARED_QUEUE_OFFSET = "TRAN_PREPARED_QUEUE_OFFSET";
  25. public static final String PROPERTY_TRANSACTION_CHECK_TIMES = "TRANSACTION_CHECK_TIMES";
  26. public static final String PROPERTY_CHECK_IMMUNITY_TIME_IN_SECONDS = "CHECK_IMMUNITY_TIME_IN_SECONDS";
  27. public static final String KEY_SEPARATOR = " ";
  28. public static final HashSet<String> STRING_HASH_SET = new HashSet<String>();
  29. static {
  30. STRING_HASH_SET.add(PROPERTY_TRACE_SWITCH);
  31. STRING_HASH_SET.add(PROPERTY_MSG_REGION);
  32. STRING_HASH_SET.add(PROPERTY_KEYS);
  33. STRING_HASH_SET.add(PROPERTY_TAGS);
  34. STRING_HASH_SET.add(PROPERTY_WAIT_STORE_MSG_OK);
  35. STRING_HASH_SET.add(PROPERTY_DELAY_TIME_LEVEL);
  36. STRING_HASH_SET.add(PROPERTY_RETRY_TOPIC);
  37. STRING_HASH_SET.add(PROPERTY_REAL_TOPIC);
  38. STRING_HASH_SET.add(PROPERTY_REAL_QUEUE_ID);
  39. STRING_HASH_SET.add(PROPERTY_TRANSACTION_PREPARED);
  40. STRING_HASH_SET.add(PROPERTY_PRODUCER_GROUP);
  41. STRING_HASH_SET.add(PROPERTY_MIN_OFFSET);
  42. STRING_HASH_SET.add(PROPERTY_MAX_OFFSET);
  43. STRING_HASH_SET.add(PROPERTY_BUYER_ID);
  44. STRING_HASH_SET.add(PROPERTY_ORIGIN_MESSAGE_ID);
  45. STRING_HASH_SET.add(PROPERTY_TRANSFER_FLAG);
  46. STRING_HASH_SET.add(PROPERTY_CORRECTION_FLAG);
  47. STRING_HASH_SET.add(PROPERTY_MQ2_FLAG);
  48. STRING_HASH_SET.add(PROPERTY_RECONSUME_TIME);
  49. STRING_HASH_SET.add(PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX);
  50. STRING_HASH_SET.add(PROPERTY_MAX_RECONSUME_TIMES);
  51. STRING_HASH_SET.add(PROPERTY_CONSUME_START_TIMESTAMP);
  52. }
  53. }

body:消息体,字节数组。需要注意生产者是用什么编码,消费者也必须使用相同的编码去解码,否则会产生乱码。

transactionId:RocketMQ 4.3.0 引入的事务消息相关的事务编号。

对于一些重要属性,Message 类还提供了一组 set 接口来进行设置,如:

  1. public class Message implements Serializable {
  2. private static final long serialVersionUID = 8445773977080406428L;
  3. public Message() {
  4. }
  5. public void setKeys(String keys) {
  6. this.putProperty(MessageConst.PROPERTY_KEYS, keys);
  7. }
  8. void putProperty(final String name, final String value) {
  9. if (null == this.properties) {
  10. this.properties = new HashMap<String, String>();
  11. }
  12. this.properties.put(name, value);
  13. }
  14. public void putUserProperty(final String name, final String value) {
  15. if (MessageConst.STRING_HASH_SET.contains(name)) {
  16. throw new RuntimeException(String.format(
  17. "The Property<%s> is used by system, input another please", name));
  18. }
  19. if (value == null || value.trim().isEmpty()
  20. || name == null || name.trim().isEmpty()) {
  21. throw new IllegalArgumentException(
  22. "The name or value of property can not be null or blank string!"
  23. );
  24. }
  25. this.putProperty(name, value);
  26. }
  27. public String getTags() {
  28. return this.getProperty(MessageConst.PROPERTY_TAGS);
  29. }
  30. public void setTags(String tags) {
  31. this.putProperty(MessageConst.PROPERTY_TAGS, tags);
  32. }
  33. public String getKeys() {
  34. return this.getProperty(MessageConst.PROPERTY_KEYS);
  35. }
  36. public void setKeys(Collection<String> keyCollection) {
  37. String keys = String.join(MessageConst.KEY_SEPARATOR, keyCollection);
  38. this.setKeys(keys);
  39. }
  40. public int getDelayTimeLevel() {
  41. String t = this.getProperty(MessageConst.PROPERTY_DELAY_TIME_LEVEL);
  42. if (t != null) {
  43. return Integer.parseInt(t);
  44. }
  45. return 0;
  46. }
  47. public void setDelayTimeLevel(int level) {
  48. this.putProperty(MessageConst.PROPERTY_DELAY_TIME_LEVEL, String.valueOf(level));
  49. }
  50. public boolean isWaitStoreMsgOK() {
  51. String result = this.getProperty(MessageConst.PROPERTY_WAIT_STORE_MSG_OK);
  52. if (null == result) {
  53. return true;
  54. }
  55. return Boolean.parseBoolean(result);
  56. }
  57. public void setWaitStoreMsgOK(boolean waitStoreMsgOK) {
  58. this.putProperty(MessageConst.PROPERTY_WAIT_STORE_MSG_OK, Boolean.toString(waitStoreMsgOK));
  59. }
  60. public void setInstanceId(String instanceId) {
  61. this.putProperty(MessageConst.PROPERTY_INSTANCE_ID, instanceId);
  62. }
  63. public String getBuyerId() {
  64. return getProperty(MessageConst.PROPERTY_BUYER_ID);
  65. }
  66. public void setBuyerId(String buyerId) {
  67. putProperty(MessageConst.PROPERTY_BUYER_ID, buyerId);
  68. }
  69. @Override
  70. public String toString() {
  71. return "Message{" +
  72. "topic='" + topic + '\'' +
  73. ", flag=" + flag +
  74. ", properties=" + properties +
  75. ", body=" + Arrays.toString(body) +
  76. ", transactionId='" + transactionId + '\'' +
  77. '}';
  78. }
  79. }

setKeys():设置消息的 key,多个 key 可以通过 MessageConst.KEY_SEPARATOR(空格)分隔或者直接使用另外一个重载方法。如果 broker 中 messageIndexEnable == true,则会根据 key 创建消息的 Hash 索引,帮助用户进行快速查询。

setTags():消息过滤的标记,用户可以订阅某个 Topic 的某个 Tag,这样 Broker 只会把订阅了 topic-tag 的消息发送给消费者。

setDelyTimeLevel():设置消息延迟处理级别,不同级别对应不同延迟时间。

setWaitStoreMsgOK():设置是否需要等待数据落地才认为消息发送成功的标记。

putUserProperty():如果还有其他扩展信息,可以存放到这里。其内部是一个 HashMap,重复调用会覆盖旧值。

对于发送方来说,上述 Message 的定义已足够使用。但对于 RocketMQ 的整个处理流程来说,还需要更多的字段信息用以记录一些必要内容,比如消息的 id、创建时间、存储时间等等。于是白尅使用另外一个实体去定义消息对象,即 MessageExt,该实体继承自 Message:

  1. public class MessageExt extends Message {
  2. private static final long serialVersionUID = 5720810158625748049L;
  3. private String brokerName;
  4. private int queueId;
  5. private int storeSize;
  6. private long queueOffset;
  7. private int sysFlag;
  8. private long bornTimestamp;
  9. private SocketAddress bornHost;
  10. private long storeTimestamp;
  11. private SocketAddress storeHost;
  12. private String msgId;
  13. private long commitLogOffset;
  14. private int bodyCRC;
  15. private int reconsumeTimes;
  16. private long preparedTransactionOffset;
  17. public MessageExt() {
  18. }
  19. public MessageExt(int queueId, long bornTimestamp, SocketAddress bornHost, long storeTimestamp,
  20. SocketAddress storeHost, String msgId) {
  21. this.queueId = queueId;
  22. this.bornTimestamp = bornTimestamp;
  23. this.bornHost = bornHost;
  24. this.storeTimestamp = storeTimestamp;
  25. this.storeHost = storeHost;
  26. this.msgId = msgId;
  27. }
  28. public static TopicFilterType parseTopicFilterType(final int sysFlag) {
  29. if ((sysFlag & MessageSysFlag.MULTI_TAGS_FLAG) == MessageSysFlag.MULTI_TAGS_FLAG) {
  30. return TopicFilterType.MULTI_TAG;
  31. }
  32. return TopicFilterType.SINGLE_TAG;
  33. }
  34. public static ByteBuffer socketAddress2ByteBuffer(final SocketAddress socketAddress, final ByteBuffer byteBuffer) {
  35. InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
  36. InetAddress address = inetSocketAddress.getAddress();
  37. if (address instanceof Inet4Address) {
  38. byteBuffer.put(inetSocketAddress.getAddress().getAddress(), 0, 4);
  39. } else {
  40. byteBuffer.put(inetSocketAddress.getAddress().getAddress(), 0, 16);
  41. }
  42. byteBuffer.putInt(inetSocketAddress.getPort());
  43. byteBuffer.flip();
  44. return byteBuffer;
  45. }
  46. public static ByteBuffer socketAddress2ByteBuffer(SocketAddress socketAddress) {
  47. InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
  48. InetAddress address = inetSocketAddress.getAddress();
  49. ByteBuffer byteBuffer;
  50. if (address instanceof Inet4Address) {
  51. byteBuffer = ByteBuffer.allocate(4 + 4);
  52. } else {
  53. byteBuffer = ByteBuffer.allocate(16 + 4);
  54. }
  55. return socketAddress2ByteBuffer(socketAddress, byteBuffer);
  56. }
  57. public ByteBuffer getBornHostBytes() {
  58. return socketAddress2ByteBuffer(this.bornHost);
  59. }
  60. public ByteBuffer getBornHostBytes(ByteBuffer byteBuffer) {
  61. return socketAddress2ByteBuffer(this.bornHost, byteBuffer);
  62. }
  63. public ByteBuffer getStoreHostBytes() {
  64. return socketAddress2ByteBuffer(this.storeHost);
  65. }
  66. public ByteBuffer getStoreHostBytes(ByteBuffer byteBuffer) {
  67. return socketAddress2ByteBuffer(this.storeHost, byteBuffer);
  68. }
  69. public String getBrokerName() {
  70. return brokerName;
  71. }
  72. public void setBrokerName(String brokerName) {
  73. this.brokerName = brokerName;
  74. }
  75. public int getQueueId() {
  76. return queueId;
  77. }
  78. public void setQueueId(int queueId) {
  79. this.queueId = queueId;
  80. }
  81. public long getBornTimestamp() {
  82. return bornTimestamp;
  83. }
  84. public void setBornTimestamp(long bornTimestamp) {
  85. this.bornTimestamp = bornTimestamp;
  86. }
  87. public SocketAddress getBornHost() {
  88. return bornHost;
  89. }
  90. public void setBornHost(SocketAddress bornHost) {
  91. this.bornHost = bornHost;
  92. }
  93. public String getBornHostString() {
  94. if (null != this.bornHost) {
  95. InetAddress inetAddress = ((InetSocketAddress) this.bornHost).getAddress();
  96. return null != inetAddress ? inetAddress.getHostAddress() : null;
  97. }
  98. return null;
  99. }
  100. public String getBornHostNameString() {
  101. if (null != this.bornHost) {
  102. if (bornHost instanceof InetSocketAddress) {
  103. // without reverse dns lookup
  104. return ((InetSocketAddress) bornHost).getHostString();
  105. }
  106. InetAddress inetAddress = ((InetSocketAddress) this.bornHost).getAddress();
  107. return null != inetAddress ? inetAddress.getHostName() : null;
  108. }
  109. return null;
  110. }
  111. public long getStoreTimestamp() {
  112. return storeTimestamp;
  113. }
  114. public void setStoreTimestamp(long storeTimestamp) {
  115. this.storeTimestamp = storeTimestamp;
  116. }
  117. public SocketAddress getStoreHost() {
  118. return storeHost;
  119. }
  120. public void setStoreHost(SocketAddress storeHost) {
  121. this.storeHost = storeHost;
  122. }
  123. public String getMsgId() {
  124. return msgId;
  125. }
  126. public void setMsgId(String msgId) {
  127. this.msgId = msgId;
  128. }
  129. public int getSysFlag() {
  130. return sysFlag;
  131. }
  132. public void setSysFlag(int sysFlag) {
  133. this.sysFlag = sysFlag;
  134. }
  135. public void setStoreHostAddressV6Flag() { this.sysFlag = this.sysFlag | MessageSysFlag.STOREHOSTADDRESS_V6_FLAG; }
  136. public void setBornHostV6Flag() { this.sysFlag = this.sysFlag | MessageSysFlag.BORNHOST_V6_FLAG; }
  137. public int getBodyCRC() {
  138. return bodyCRC;
  139. }
  140. public void setBodyCRC(int bodyCRC) {
  141. this.bodyCRC = bodyCRC;
  142. }
  143. public long getQueueOffset() {
  144. return queueOffset;
  145. }
  146. public void setQueueOffset(long queueOffset) {
  147. this.queueOffset = queueOffset;
  148. }
  149. public long getCommitLogOffset() {
  150. return commitLogOffset;
  151. }
  152. public void setCommitLogOffset(long physicOffset) {
  153. this.commitLogOffset = physicOffset;
  154. }
  155. public int getStoreSize() {
  156. return storeSize;
  157. }
  158. public void setStoreSize(int storeSize) {
  159. this.storeSize = storeSize;
  160. }
  161. public int getReconsumeTimes() {
  162. return reconsumeTimes;
  163. }
  164. public void setReconsumeTimes(int reconsumeTimes) {
  165. this.reconsumeTimes = reconsumeTimes;
  166. }
  167. public long getPreparedTransactionOffset() {
  168. return preparedTransactionOffset;
  169. }
  170. public void setPreparedTransactionOffset(long preparedTransactionOffset) {
  171. this.preparedTransactionOffset = preparedTransactionOffset;
  172. }
  173. @Override
  174. public String toString() {
  175. return "MessageExt [brokerName=" + brokerName + ", queueId=" + queueId + ", storeSize=" + storeSize + ", queueOffset=" + queueOffset
  176. + ", sysFlag=" + sysFlag + ", bornTimestamp=" + bornTimestamp + ", bornHost=" + bornHost
  177. + ", storeTimestamp=" + storeTimestamp + ", storeHost=" + storeHost + ", msgId=" + msgId
  178. + ", commitLogOffset=" + commitLogOffset + ", bodyCRC=" + bodyCRC + ", reconsumeTimes="
  179. + reconsumeTimes + ", preparedTransactionOffset=" + preparedTransactionOffset
  180. + ", toString()=" + super.toString() + "]";
  181. }
  182. }

queueId:记录 MessageQueue 编号,消息会被发送到 Topic 下的 MessageQueue

storeSize:记录消息在 Broker 存盘中大小

queueOffset:记录在 ConsumeQueue 中的偏移

sysFlag:记录一些系统标志的开状态态,org.apache.rocketmq.common.sysflag.MessageSysFlag 中定义了系统标识

bornTimestamp:记录消息创建时间,在 Producer 发送消息时设置

storeHost:记录存储该消息的 Broker 地址

msgId:消息 Id

commitLogOffset:记录在 Broker 中存储便宜

bodyCRC:消息内容 CRC 校验值

reconsumeTimes:记录消息重试消费次数

preparedTransactionOffset:事务消息相关字段

Message 还有一个名为 MessageConst.PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX 的属性:

public static final String PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX = "UNIQ_KEY";

在消息发送时由 Producer 生成创建。msgId 则是消息在 Broker 端进行存储时通过MessageDecoder.createMessageId 方法生成的:

  1. public class MessageDecoder {
  2. // public final static int MSG_ID_LENGTH = 8 + 8;
  3. public final static Charset CHARSET_UTF8 = StandardCharsets.UTF_8;
  4. public final static int MESSAGE_MAGIC_CODE_POSTION = 4;
  5. public final static int MESSAGE_FLAG_POSTION = 16;
  6. public final static int MESSAGE_PHYSIC_OFFSET_POSTION = 28;
  7. // public final static int MESSAGE_STORE_TIMESTAMP_POSTION = 56;
  8. public final static int MESSAGE_MAGIC_CODE = -626843481;
  9. public static final char NAME_VALUE_SEPARATOR = 1;
  10. public static final char PROPERTY_SEPARATOR = 2;
  11. public static final int PHY_POS_POSITION = 4 + 4 + 4 + 4 + 4 + 8;
  12. public static final int QUEUE_OFFSET_POSITION = 4 + 4 + 4 + 4 + 4;
  13. public static final int SYSFLAG_POSITION = 4 + 4 + 4 + 4 + 4 + 8 + 8;
  14. // public static final int BODY_SIZE_POSITION = 4 // 1 TOTALSIZE
  15. // + 4 // 2 MAGICCODE
  16. // + 4 // 3 BODYCRC
  17. // + 4 // 4 QUEUEID
  18. // + 4 // 5 FLAG
  19. // + 8 // 6 QUEUEOFFSET
  20. // + 8 // 7 PHYSICALOFFSET
  21. // + 4 // 8 SYSFLAG
  22. // + 8 // 9 BORNTIMESTAMP
  23. // + 8 // 10 BORNHOST
  24. // + 8 // 11 STORETIMESTAMP
  25. // + 8 // 12 STOREHOSTADDRESS
  26. // + 4 // 13 RECONSUMETIMES
  27. // + 8; // 14 Prepared Transaction Offset
  28. public static String createMessageId(final ByteBuffer input, final ByteBuffer addr, final long offset) {
  29. input.flip();
  30. int msgIDLength = addr.limit() == 8 ? 16 : 28;
  31. input.limit(msgIDLength);
  32. input.put(addr);
  33. input.putLong(offset);
  34. return UtilAll.bytes2string(input.array());
  35. }
  36. public static String createMessageId(SocketAddress socketAddress, long transactionIdhashCode) {
  37. InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
  38. int msgIDLength = inetSocketAddress.getAddress() instanceof Inet4Address ? 16 : 28;
  39. ByteBuffer byteBuffer = ByteBuffer.allocate(msgIDLength);
  40. byteBuffer.put(inetSocketAddress.getAddress().getAddress());
  41. byteBuffer.putInt(inetSocketAddress.getPort());
  42. byteBuffer.putLong(transactionIdhashCode);
  43. byteBuffer.flip();
  44. return UtilAll.bytes2string(byteBuffer.array());
  45. }
  46. public static MessageId decodeMessageId(final String msgId) throws UnknownHostException {
  47. byte[] bytes = UtilAll.string2bytes(msgId);
  48. ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
  49. // address(ip+port)
  50. byte[] ip = new byte[msgId.length() == 32 ? 4 : 16];
  51. byteBuffer.get(ip);
  52. int port = byteBuffer.getInt();
  53. SocketAddress address = new InetSocketAddress(InetAddress.getByAddress(ip), port);
  54. // offset
  55. long offset = byteBuffer.getLong();
  56. return new MessageId(address, offset);
  57. }
  58. /**
  59. * Just decode properties from msg buffer.
  60. *
  61. * @param byteBuffer msg commit log buffer.
  62. */
  63. public static Map<String, String> decodeProperties(ByteBuffer byteBuffer) {
  64. int sysFlag = byteBuffer.getInt(SYSFLAG_POSITION);
  65. int bornhostLength = (sysFlag & MessageSysFlag.BORNHOST_V6_FLAG) == 0 ? 8 : 20;
  66. int storehostAddressLength = (sysFlag & MessageSysFlag.STOREHOSTADDRESS_V6_FLAG) == 0 ? 8 : 20;
  67. int bodySizePosition = 4 // 1 TOTALSIZE
  68. + 4 // 2 MAGICCODE
  69. + 4 // 3 BODYCRC
  70. + 4 // 4 QUEUEID
  71. + 4 // 5 FLAG
  72. + 8 // 6 QUEUEOFFSET
  73. + 8 // 7 PHYSICALOFFSET
  74. + 4 // 8 SYSFLAG
  75. + 8 // 9 BORNTIMESTAMP
  76. + bornhostLength // 10 BORNHOST
  77. + 8 // 11 STORETIMESTAMP
  78. + storehostAddressLength // 12 STOREHOSTADDRESS
  79. + 4 // 13 RECONSUMETIMES
  80. + 8; // 14 Prepared Transaction Offset
  81. int topicLengthPosition = bodySizePosition + 4 + byteBuffer.getInt(bodySizePosition);
  82. byte topicLength = byteBuffer.get(topicLengthPosition);
  83. short propertiesLength = byteBuffer.getShort(topicLengthPosition + 1 + topicLength);
  84. byteBuffer.position(topicLengthPosition + 1 + topicLength + 2);
  85. if (propertiesLength > 0) {
  86. byte[] properties = new byte[propertiesLength];
  87. byteBuffer.get(properties);
  88. String propertiesString = new String(properties, CHARSET_UTF8);
  89. Map<String, String> map = string2messageProperties(propertiesString);
  90. return map;
  91. }
  92. return null;
  93. }
  94. public static MessageExt decode(ByteBuffer byteBuffer) {
  95. return decode(byteBuffer, true, true, false);
  96. }
  97. public static MessageExt clientDecode(ByteBuffer byteBuffer, final boolean readBody) {
  98. return decode(byteBuffer, readBody, true, true);
  99. }
  100. public static MessageExt decode(ByteBuffer byteBuffer, final boolean readBody) {
  101. return decode(byteBuffer, readBody, true, false);
  102. }
  103. public static byte[] encode(MessageExt messageExt, boolean needCompress) throws Exception {
  104. byte[] body = messageExt.getBody();
  105. byte[] topics = messageExt.getTopic().getBytes(CHARSET_UTF8);
  106. byte topicLen = (byte) topics.length;
  107. String properties = messageProperties2String(messageExt.getProperties());
  108. byte[] propertiesBytes = properties.getBytes(CHARSET_UTF8);
  109. short propertiesLength = (short) propertiesBytes.length;
  110. int sysFlag = messageExt.getSysFlag();
  111. int bornhostLength = (sysFlag & MessageSysFlag.BORNHOST_V6_FLAG) == 0 ? 8 : 20;
  112. int storehostAddressLength = (sysFlag & MessageSysFlag.STOREHOSTADDRESS_V6_FLAG) == 0 ? 8 : 20;
  113. byte[] newBody = messageExt.getBody();
  114. if (needCompress && (sysFlag & MessageSysFlag.COMPRESSED_FLAG) == MessageSysFlag.COMPRESSED_FLAG) {
  115. Compressor compressor = CompressorFactory.getCompressor(MessageSysFlag.getCompressionType(sysFlag));
  116. newBody = compressor.compress(body, 5);
  117. }
  118. int bodyLength = newBody.length;
  119. int storeSize = messageExt.getStoreSize();
  120. ByteBuffer byteBuffer;
  121. if (storeSize > 0) {
  122. byteBuffer = ByteBuffer.allocate(storeSize);
  123. } else {
  124. storeSize = 4 // 1 TOTALSIZE
  125. + 4 // 2 MAGICCODE
  126. + 4 // 3 BODYCRC
  127. + 4 // 4 QUEUEID
  128. + 4 // 5 FLAG
  129. + 8 // 6 QUEUEOFFSET
  130. + 8 // 7 PHYSICALOFFSET
  131. + 4 // 8 SYSFLAG
  132. + 8 // 9 BORNTIMESTAMP
  133. + bornhostLength // 10 BORNHOST
  134. + 8 // 11 STORETIMESTAMP
  135. + storehostAddressLength // 12 STOREHOSTADDRESS
  136. + 4 // 13 RECONSUMETIMES
  137. + 8 // 14 Prepared Transaction Offset
  138. + 4 + bodyLength // 14 BODY
  139. + 1 + topicLen // 15 TOPIC
  140. + 2 + propertiesLength // 16 propertiesLength
  141. + 0;
  142. byteBuffer = ByteBuffer.allocate(storeSize);
  143. }
  144. // 1 TOTALSIZE
  145. byteBuffer.putInt(storeSize);
  146. // 2 MAGICCODE
  147. byteBuffer.putInt(MESSAGE_MAGIC_CODE);
  148. // 3 BODYCRC
  149. int bodyCRC = messageExt.getBodyCRC();
  150. byteBuffer.putInt(bodyCRC);
  151. // 4 QUEUEID
  152. int queueId = messageExt.getQueueId();
  153. byteBuffer.putInt(queueId);
  154. // 5 FLAG
  155. int flag = messageExt.getFlag();
  156. byteBuffer.putInt(flag);
  157. // 6 QUEUEOFFSET
  158. long queueOffset = messageExt.getQueueOffset();
  159. byteBuffer.putLong(queueOffset);
  160. // 7 PHYSICALOFFSET
  161. long physicOffset = messageExt.getCommitLogOffset();
  162. byteBuffer.putLong(physicOffset);
  163. // 8 SYSFLAG
  164. byteBuffer.putInt(sysFlag);
  165. // 9 BORNTIMESTAMP
  166. long bornTimeStamp = messageExt.getBornTimestamp();
  167. byteBuffer.putLong(bornTimeStamp);
  168. // 10 BORNHOST
  169. InetSocketAddress bornHost = (InetSocketAddress) messageExt.getBornHost();
  170. byteBuffer.put(bornHost.getAddress().getAddress());
  171. byteBuffer.putInt(bornHost.getPort());
  172. // 11 STORETIMESTAMP
  173. long storeTimestamp = messageExt.getStoreTimestamp();
  174. byteBuffer.putLong(storeTimestamp);
  175. // 12 STOREHOST
  176. InetSocketAddress serverHost = (InetSocketAddress) messageExt.getStoreHost();
  177. byteBuffer.put(serverHost.getAddress().getAddress());
  178. byteBuffer.putInt(serverHost.getPort());
  179. // 13 RECONSUMETIMES
  180. int reconsumeTimes = messageExt.getReconsumeTimes();
  181. byteBuffer.putInt(reconsumeTimes);
  182. // 14 Prepared Transaction Offset
  183. long preparedTransactionOffset = messageExt.getPreparedTransactionOffset();
  184. byteBuffer.putLong(preparedTransactionOffset);
  185. // 15 BODY
  186. byteBuffer.putInt(bodyLength);
  187. byteBuffer.put(newBody);
  188. // 16 TOPIC
  189. byteBuffer.put(topicLen);
  190. byteBuffer.put(topics);
  191. // 17 properties
  192. byteBuffer.putShort(propertiesLength);
  193. byteBuffer.put(propertiesBytes);
  194. return byteBuffer.array();
  195. }
  196. public static MessageExt decode(
  197. ByteBuffer byteBuffer, final boolean readBody, final boolean deCompressBody) {
  198. return decode(byteBuffer, readBody, deCompressBody, false);
  199. }
  200. public static MessageExt decode(
  201. ByteBuffer byteBuffer, final boolean readBody, final boolean deCompressBody, final boolean isClient) {
  202. try {
  203. MessageExt msgExt;
  204. if (isClient) {
  205. msgExt = new MessageClientExt();
  206. } else {
  207. msgExt = new MessageExt();
  208. }
  209. // 1 TOTALSIZE
  210. int storeSize = byteBuffer.getInt();
  211. msgExt.setStoreSize(storeSize);
  212. // 2 MAGICCODE
  213. byteBuffer.getInt();
  214. // 3 BODYCRC
  215. int bodyCRC = byteBuffer.getInt();
  216. msgExt.setBodyCRC(bodyCRC);
  217. // 4 QUEUEID
  218. int queueId = byteBuffer.getInt();
  219. msgExt.setQueueId(queueId);
  220. // 5 FLAG
  221. int flag = byteBuffer.getInt();
  222. msgExt.setFlag(flag);
  223. // 6 QUEUEOFFSET
  224. long queueOffset = byteBuffer.getLong();
  225. msgExt.setQueueOffset(queueOffset);
  226. // 7 PHYSICALOFFSET
  227. long physicOffset = byteBuffer.getLong();
  228. msgExt.setCommitLogOffset(physicOffset);
  229. // 8 SYSFLAG
  230. int sysFlag = byteBuffer.getInt();
  231. msgExt.setSysFlag(sysFlag);
  232. // 9 BORNTIMESTAMP
  233. long bornTimeStamp = byteBuffer.getLong();
  234. msgExt.setBornTimestamp(bornTimeStamp);
  235. // 10 BORNHOST
  236. int bornhostIPLength = (sysFlag & MessageSysFlag.BORNHOST_V6_FLAG) == 0 ? 4 : 16;
  237. byte[] bornHost = new byte[bornhostIPLength];
  238. byteBuffer.get(bornHost, 0, bornhostIPLength);
  239. int port = byteBuffer.getInt();
  240. msgExt.setBornHost(new InetSocketAddress(InetAddress.getByAddress(bornHost), port));
  241. // 11 STORETIMESTAMP
  242. long storeTimestamp = byteBuffer.getLong();
  243. msgExt.setStoreTimestamp(storeTimestamp);
  244. // 12 STOREHOST
  245. int storehostIPLength = (sysFlag & MessageSysFlag.STOREHOSTADDRESS_V6_FLAG) == 0 ? 4 : 16;
  246. byte[] storeHost = new byte[storehostIPLength];
  247. byteBuffer.get(storeHost, 0, storehostIPLength);
  248. port = byteBuffer.getInt();
  249. msgExt.setStoreHost(new InetSocketAddress(InetAddress.getByAddress(storeHost), port));
  250. // 13 RECONSUMETIMES
  251. int reconsumeTimes = byteBuffer.getInt();
  252. msgExt.setReconsumeTimes(reconsumeTimes);
  253. // 14 Prepared Transaction Offset
  254. long preparedTransactionOffset = byteBuffer.getLong();
  255. msgExt.setPreparedTransactionOffset(preparedTransactionOffset);
  256. // 15 BODY
  257. int bodyLen = byteBuffer.getInt();
  258. if (bodyLen > 0) {
  259. if (readBody) {
  260. byte[] body = new byte[bodyLen];
  261. byteBuffer.get(body);
  262. // uncompress body
  263. if (deCompressBody && (sysFlag & MessageSysFlag.COMPRESSED_FLAG) == MessageSysFlag.COMPRESSED_FLAG) {
  264. Compressor compressor = CompressorFactory.getCompressor(MessageSysFlag.getCompressionType(sysFlag));
  265. body = compressor.decompress(body);
  266. }
  267. msgExt.setBody(body);
  268. } else {
  269. byteBuffer.position(byteBuffer.position() + bodyLen);
  270. }
  271. }
  272. // 16 TOPIC
  273. byte topicLen = byteBuffer.get();
  274. byte[] topic = new byte[(int) topicLen];
  275. byteBuffer.get(topic);
  276. msgExt.setTopic(new String(topic, CHARSET_UTF8));
  277. // 17 properties
  278. short propertiesLength = byteBuffer.getShort();
  279. if (propertiesLength > 0) {
  280. byte[] properties = new byte[propertiesLength];
  281. byteBuffer.get(properties);
  282. String propertiesString = new String(properties, CHARSET_UTF8);
  283. Map<String, String> map = string2messageProperties(propertiesString);
  284. msgExt.setProperties(map);
  285. }
  286. int msgIDLength = storehostIPLength + 4 + 8;
  287. ByteBuffer byteBufferMsgId = ByteBuffer.allocate(msgIDLength);
  288. String msgId = createMessageId(byteBufferMsgId, msgExt.getStoreHostBytes(), msgExt.getCommitLogOffset());
  289. msgExt.setMsgId(msgId);
  290. if (isClient) {
  291. ((MessageClientExt) msgExt).setOffsetMsgId(msgId);
  292. }
  293. return msgExt;
  294. } catch (Exception e) {
  295. byteBuffer.position(byteBuffer.limit());
  296. }
  297. return null;
  298. }
  299. public static List<MessageExt> decodes(ByteBuffer byteBuffer) {
  300. return decodes(byteBuffer, true);
  301. }
  302. public static List<MessageExt> decodes(ByteBuffer byteBuffer, final boolean readBody) {
  303. List<MessageExt> msgExts = new ArrayList<MessageExt>();
  304. while (byteBuffer.hasRemaining()) {
  305. MessageExt msgExt = clientDecode(byteBuffer, readBody);
  306. if (null != msgExt) {
  307. msgExts.add(msgExt);
  308. } else {
  309. break;
  310. }
  311. }
  312. return msgExts;
  313. }
  314. public static String messageProperties2String(Map<String, String> properties) {
  315. if (properties == null) {
  316. return "";
  317. }
  318. int len = 0;
  319. for (final Map.Entry<String, String> entry : properties.entrySet()) {
  320. final String name = entry.getKey();
  321. final String value = entry.getValue();
  322. if (value == null) {
  323. continue;
  324. }
  325. if (name != null) {
  326. len += name.length();
  327. }
  328. len += value.length();
  329. len += 2; // separator
  330. }
  331. StringBuilder sb = new StringBuilder(len);
  332. if (properties != null) {
  333. for (final Map.Entry<String, String> entry : properties.entrySet()) {
  334. final String name = entry.getKey();
  335. final String value = entry.getValue();
  336. if (value == null) {
  337. continue;
  338. }
  339. sb.append(name);
  340. sb.append(NAME_VALUE_SEPARATOR);
  341. sb.append(value);
  342. sb.append(PROPERTY_SEPARATOR);
  343. }
  344. if (sb.length() > 0) {
  345. sb.deleteCharAt(sb.length() - 1);
  346. }
  347. }
  348. return sb.toString();
  349. }
  350. public static Map<String, String> string2messageProperties(final String properties) {
  351. Map<String, String> map = new HashMap<String, String>();
  352. if (properties != null) {
  353. int len = properties.length();
  354. int index = 0;
  355. while (index < len) {
  356. int newIndex = properties.indexOf(PROPERTY_SEPARATOR, index);
  357. if (newIndex < 0) {
  358. newIndex = len;
  359. }
  360. if (newIndex - index >= 3) {
  361. int kvSepIndex = properties.indexOf(NAME_VALUE_SEPARATOR, index);
  362. if (kvSepIndex > index && kvSepIndex < newIndex - 1) {
  363. String k = properties.substring(index, kvSepIndex);
  364. String v = properties.substring(kvSepIndex + 1, newIndex);
  365. map.put(k, v);
  366. }
  367. }
  368. index = newIndex + 1;
  369. }
  370. }
  371. return map;
  372. }
  373. public static byte[] encodeMessage(Message message) {
  374. //only need flag, body, properties
  375. byte[] body = message.getBody();
  376. int bodyLen = body.length;
  377. String properties = messageProperties2String(message.getProperties());
  378. byte[] propertiesBytes = properties.getBytes(CHARSET_UTF8);
  379. //note properties length must not more than Short.MAX
  380. int propsLen = propertiesBytes.length;
  381. if (propsLen > Short.MAX_VALUE)
  382. throw new RuntimeException(String.format("Properties size of message exceeded, properties size: {}, maxSize: {}.", propsLen, Short.MAX_VALUE));
  383. short propertiesLength = (short) propsLen;
  384. int sysFlag = message.getFlag();
  385. int storeSize = 4 // 1 TOTALSIZE
  386. + 4 // 2 MAGICCOD
  387. + 4 // 3 BODYCRC
  388. + 4 // 4 FLAG
  389. + 4 + bodyLen // 4 BODY
  390. + 2 + propertiesLength;
  391. ByteBuffer byteBuffer = ByteBuffer.allocate(storeSize);
  392. // 1 TOTALSIZE
  393. byteBuffer.putInt(storeSize);
  394. // 2 MAGICCODE
  395. byteBuffer.putInt(0);
  396. // 3 BODYCRC
  397. byteBuffer.putInt(0);
  398. // 4 FLAG
  399. int flag = message.getFlag();
  400. byteBuffer.putInt(flag);
  401. // 5 BODY
  402. byteBuffer.putInt(bodyLen);
  403. byteBuffer.put(body);
  404. // 6 properties
  405. byteBuffer.putShort(propertiesLength);
  406. byteBuffer.put(propertiesBytes);
  407. return byteBuffer.array();
  408. }
  409. public static Message decodeMessage(ByteBuffer byteBuffer) throws Exception {
  410. Message message = new Message();
  411. // 1 TOTALSIZE
  412. byteBuffer.getInt();
  413. // 2 MAGICCODE
  414. byteBuffer.getInt();
  415. // 3 BODYCRC
  416. byteBuffer.getInt();
  417. // 4 FLAG
  418. int flag = byteBuffer.getInt();
  419. message.setFlag(flag);
  420. // 5 BODY
  421. int bodyLen = byteBuffer.getInt();
  422. byte[] body = new byte[bodyLen];
  423. byteBuffer.get(body);
  424. message.setBody(body);
  425. // 6 properties
  426. short propertiesLen = byteBuffer.getShort();
  427. byte[] propertiesBytes = new byte[propertiesLen];
  428. byteBuffer.get(propertiesBytes);
  429. message.setProperties(string2messageProperties(new String(propertiesBytes, CHARSET_UTF8)));
  430. return message;
  431. }
  432. public static byte[] encodeMessages(List<Message> messages) {
  433. //TO DO refactor, accumulate in one buffer, avoid copies
  434. List<byte[]> encodedMessages = new ArrayList<byte[]>(messages.size());
  435. int allSize = 0;
  436. for (Message message : messages) {
  437. byte[] tmp = encodeMessage(message);
  438. encodedMessages.add(tmp);
  439. allSize += tmp.length;
  440. }
  441. byte[] allBytes = new byte[allSize];
  442. int pos = 0;
  443. for (byte[] bytes : encodedMessages) {
  444. System.arraycopy(bytes, 0, allBytes, pos, bytes.length);
  445. pos += bytes.length;
  446. }
  447. return allBytes;
  448. }
  449. public static List<Message> decodeMessages(ByteBuffer byteBuffer) throws Exception {
  450. //TO DO add a callback for processing, avoid creating lists
  451. List<Message> msgs = new ArrayList<Message>();
  452. while (byteBuffer.hasRemaining()) {
  453. Message msg = decodeMessage(byteBuffer);
  454. msgs.add(msg);
  455. }
  456. return msgs;
  457. }
  458. }

这个 MsgId 是在 Broker 生成的,Producer 在发送消息时没有该信息,Consumer 在消费消息时则能获取到该值。

RocketMQ 支持普通消息、分区有序消息、全局有序消息、延迟消息和事务消息。

普通消息:普通消息也称为并发消息,和传统的队列相比,并发消息没有顺序,但是生产者和消费者都是并行进行的,单机性能可达十万级别的 tps。

分区顺序消息:分区有序消息又称普通有序消息,与 Kafka 的分区类似,把一个 Topic 消息分为多个分区“保存”起来,在一个分区内的消息就是传统的队列,遵循 FIFO(先进先出)原则,所以是有序的,于是消费者通过同一个消息队列(Topic 分区,称作 Message Queue) 收到的消息也是有顺序的,但是不同消息队列收到的消息则可能是无顺序的。

全局顺序消息:全局有序消息又称严格顺序消息,消费者收到的所有消息均是有顺序的。可以理解为把一个 Topic 的分区数设置为 1,那么该 Topic 中的消息就是单分区,所有的消息都遵循 FIFO(先进先出)队列,所以是有序的。

事务消息:RocketMQ 事务消息(Transactional Message)是指应用本地事务和发送消息操作可以被定义到全局事务中,要么同时成功,要么同时失败。RocketMQ 的事务消息提供类似 X/Open XA 的分布事务功能,通过事务消息能达到分布式事务的最终一致。主要涉及分布式事务,即需要保证在多个操作同时成功或者同时失败时消费者才能消费消息。RocketMQ 通过发送 Half 消息、处理本地事务、提交消息或者回滚消息可以优雅地实现分布式事务。

延迟消息:消息发送到 broker 后,不会立即被消费,等待特定时间投递给真正的 topic。也可以理解为消费者要在一定时间之后,或者指定某个时间点才可以消费消息。在没有延迟消息时,基本的做法是给予定时计划任务调度,定时发送消息。在 RocketMQ 中只需要在发送消息时设置延迟级别即可实现。 broker 中有配置项 messageDelayLevel:

private String messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";

总共 18 个 level。可以配置自定义 messageDelayLevel。注意,messageDelayLevel 是 broker 的属性,不属于某个 topic。发消息时,设置 delayLevel 等级即可:msg.setDelayLevel(level)。level有以下三种情况:

  • level == 0,消息为非延迟消息
  • 1 <= leve l<= maxLevel,消息延迟特定时间,例如 level == 1,表示延迟 1s
  • level > maxLevel,则 level == maxLevel,例如 level == 20,表示延迟 2h

定时消息会暂存在名为 SCHEDULE_TOPIC_XXXX 的 topic 中,并根据 delayTimeLevel 存入特定的 queue,queueId = delayTimeLevel - 1,即一个 queue 只存相同延迟的消息,保证具有相同发送延迟的消息能够顺序消费。broker 会调度地消费 SCHEDULE_TOPIC_XXXX,将消息写入真实的 topic。

需要注意的是,定时消息会在第一次写入和调度写入真实 topic 时都会计数,因此发送数量、tps 都会变高。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/603645
推荐阅读
相关标签
  

闽ICP备14008679号