---
title: "MetaQ技术内幕——源码分析(二)"
author: "wbj0110"
date: "2014-05-30T14:58:21Z"
tags: ["metaq"]
categories: ["编程语言"]
slug: "metaq"
draft: false
lastmod: "2014-05-30T14:58:21Z"
id: 2074275
url: "https://soledede.iteye.com/blog/2074275"
---

消息，是MetaQ最重要的资源，在分析MetaQ之前必须了解的概念，我们所做的一切都是围绕消息进行的，让我们看看MetaQ中消息的定义是怎样的，MetaQ的类Message定义了消息的格式：

Java代码 [![复制代码](http://udukwilliam.iteye.com/images/icon_copy.gif)](http://udukwilliam.iteye.com/blog/1929253 "复制代码") [![收藏代码](http://udukwilliam.iteye.com/images/icon_star.png)![](http://udukwilliam.iteye.com/images/spinner.gif)](http://blog.csdn.net/qiaochao911/article/details/23440633 "收藏这段代码")

01. public class Messageimplements Serializable {
02. private long id;//消息的ID
03. private String topic; //消息属于哪个主题
04. private byte\[] data; //消息的内容
05. private String attribute; //消息的属性
06. private int flag;//属性标志位，如果属性不为空，则该标志位true
07. private Partition partition; //该主题下的哪个分区，简单的理解为发送到该主题下的哪个队列
08. private transientboolean readOnly; //消息是否只读
09. private transientboolean rollbackOnly = false;//该消息是否需要回滚，主要用于事务实现的需要
10. }

**\[java]** [view plain](http://blog.csdn.net/qiaochao911/article/details/23440633 "view plain")[copy](http://blog.csdn.net/qiaochao911/article/details/23440633 "copy")[![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/286558 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/286558/fork "派生到我的代码片")

 

01. public class Message implements Serializable {
02. private long id; //消息的ID
03. private String topic; //消息属于哪个主题
04. private byte\[] data;  //消息的内容
05. private String attribute; //消息的属性
06. private int flag; //属性标志位，如果属性不为空，则该标志位true
07. private Partition partition; //该主题下的哪个分区，简单的理解为发送到该主题下的哪个队列
08. private transient boolean readOnly; //消息是否只读
09. private transient boolean rollbackOnly = false; //该消息是否需要回滚，主要用于事务实现的需要
10. }

从对消息的定义，我们可以看出消息都有一个唯一的ID，并且归属于某个主题，发送到该主题下的某个分区，具有一些基本属性。

 

MetaQ分为Broker和Client以及Zookeeper，系统结构如下：

![](http://dl2.iteye.com/upload/attachment/0088/5290/faa935d9-1cd4-34bd-8185-4ce31ccc2d56.jpg "点击查看原始大小图片")

 

 

下面我们先分析Broker源码。

 

Broker主要围绕发送消息和消费消息的主线进行，对于Broker来说就是输入、输出流的处理。在该主线下，Broker主要分为如下模块：网络传输模块、消息存储模块、消息统计模块以及事务模块，本篇首先针对独立性较强的消息存储模块进行分析。

 

在进行存储模块分析之前，我们得了解Broker中的一个重要的类MetaConfig，MetaConfig是Broker配置加载器，通过MetaConfig可以获取到各模块相关的配置，所以MetaConfig是贯穿所有模块的类。MetaConfig实现MetaConfigMBean接口，该接口定义如下：

Java代码 [![复制代码](http://udukwilliam.iteye.com/images/icon_copy.gif)](http://udukwilliam.iteye.com/blog/1929253 "复制代码") [![收藏代码](http://udukwilliam.iteye.com/images/icon_star.png)![](http://udukwilliam.iteye.com/images/spinner.gif)](http://blog.csdn.net/qiaochao911/article/details/23440633 "收藏这段代码")

01. public interface MetaConfigMBean {
02. /\**
03. \* Reload topics configuration
04. \*/
05. public void reload();
06. /\*\*关闭分区 \*/
07. public void closePartitions(String topic,int start, int end);
08. /\*\*打开一个topic的所有分区 \*/
09. public void openPartitions(String topic);
10. }

**\[java]** [view plain](http://blog.csdn.net/qiaochao911/article/details/23440633 "view plain")[copy](http://blog.csdn.net/qiaochao911/article/details/23440633 "copy")[![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/286558 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/286558/fork "派生到我的代码片")

 

01. public interface MetaConfigMBean {
02. /\**
03. * Reload topics configuration
04. \*/
05. public void reload();
06. /\*\*关闭分区 \*/
07. public void closePartitions(String topic, int start, int end);
08. /\*\*打开一个topic的所有分区 \*/
09. public void openPartitions(String topic);
10. }

 

MetaConfig注册到了MBeanServer上，所以可以通过JMX协议重新加载配置以及关闭和打开分区。为了加载的配置立即生效，MetaConfig内置了一个通知机制，可以通过向MetaConfig注册监听器的方式关注相关配置的变化，监听器需实现PropertyChangeListener接口。

Java代码 [![复制代码](http://udukwilliam.iteye.com/images/icon_copy.gif)](http://udukwilliam.iteye.com/blog/1929253 "复制代码") [![收藏代码](http://udukwilliam.iteye.com/images/icon_star.png)![](http://udukwilliam.iteye.com/images/spinner.gif)](http://blog.csdn.net/qiaochao911/article/details/23440633 "收藏这段代码")

1. public void addPropertyChangeListener(final String propertyName,finalPropertyChangeListener listener) {
2. this.propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
3. }
4. public void removePropertyChangeListener(final PropertyChangeListener listener) {
5. this.propertyChangeSupport.removePropertyChangeListener(listener);
6. }

**\[java]** [view plain](http://blog.csdn.net/qiaochao911/article/details/23440633 "view plain")[copy](http://blog.csdn.net/qiaochao911/article/details/23440633 "copy")[![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/286558 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/286558/fork "派生到我的代码片")

 

1. public void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener) {
2. this.propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
3. }
4. public void removePropertyChangeListener(final PropertyChangeListener listener) {
5. this.propertyChangeSupport.removePropertyChangeListener(listener);
6. }

 

目前MetaConfig发出的事件通知有三种：配置文件发生变化（configFileChecksum）、主题发生变化（topics，topicConfigMap）以及刷新存储的频率发生变化（unflushInterval），代码如下：

Java代码 [![复制代码](http://udukwilliam.iteye.com/images/icon_copy.gif)](http://udukwilliam.iteye.com/blog/1929253 "复制代码") [![收藏代码](http://udukwilliam.iteye.com/images/icon_star.png)![](http://udukwilliam.iteye.com/images/spinner.gif)](http://blog.csdn.net/qiaochao911/article/details/23440633 "收藏这段代码")

01. //configFileChecksum通知
02. private Ini createIni(final File file)throws IOException, InvalidFileFormatException {
03. ……
04. this.propertyChangeSupport.firePropertyChange("configFileChecksum",null, null);
05. return conf;
06. }
07. public void setConfigFileChecksum(long configFileChecksum) {
08. this.configFileChecksum = configFileChecksum;
09. this.propertyChangeSupport.firePropertyChange("configFileChecksum",null, null);
10. }
11. //topics、topicConfigMap和unflushInterval通知
12. private void populateTopicsConfig(final Ini conf) {
13. ……
14. if (!newTopicConfigMap.equals(this.topicConfigMap)) {
15. this.topics = newTopics;
16. this.topicConfigMap = newTopicConfigMap;
17. this.propertyChangeSupport.firePropertyChange("topics",null, null);
18. this.propertyChangeSupport.firePropertyChange("topicConfigMap",null, null);
19. }
20. this.propertyChangeSupport.firePropertyChange("unflushInterval",null, null);
21. ……

**\[java]** [view plain](http://blog.csdn.net/qiaochao911/article/details/23440633 "view plain")[copy](http://blog.csdn.net/qiaochao911/article/details/23440633 "copy")[![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/286558 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/286558/fork "派生到我的代码片")

 

01. //configFileChecksum通知
02. private Ini createIni(final File file) throws IOException, InvalidFileFormatException {
03. ……
04. this.propertyChangeSupport.firePropertyChange("configFileChecksum", null, null);
05. return conf;
06. }
07. public void setConfigFileChecksum(long configFileChecksum) {
08. this.configFileChecksum = configFileChecksum;
09. this.propertyChangeSupport.firePropertyChange("configFileChecksum", null, null);
10. }
11. //topics、topicConfigMap和unflushInterval通知
12. private void populateTopicsConfig(final Ini conf) {
13. ……
14. if (!newTopicConfigMap.equals(this.topicConfigMap)) {
15. this.topics = newTopics;
16. this.topicConfigMap = newTopicConfigMap;
17. this.propertyChangeSupport.firePropertyChange("topics", null, null);
18. this.propertyChangeSupport.firePropertyChange("topicConfigMap", null, null);
19. }
20. this.propertyChangeSupport.firePropertyChange("unflushInterval", null, null);
21. ……

需要注意的是，调用reload方法时，只对topic的配置生效，对全局配置不生效，只重载topic的配置。

 

好吧，废话了许多，让我们正式进入存储模块的分析吧。

 

Broker的存储模块用于存储Client发送的等待被消费的消息，Broker采用文件存储的方式来存储消息，存储模块类图如下：

 

![](http://dl2.iteye.com/upload/attachment/0088/5215/005275b0-c634-3d10-bed1-8dfa43829f1a.jpg "点击查看原始大小图片")  
 

 

MessageSet代表一个消息集合，可能是一个文件也可能是文件的一部分，其定义如下：

 

Java代码 [![复制代码](http://udukwilliam.iteye.com/images/icon_copy.gif)](http://udukwilliam.iteye.com/blog/1929253 "复制代码") [![收藏代码](http://udukwilliam.iteye.com/images/icon_star.png)![](http://udukwilliam.iteye.com/images/spinner.gif)](http://blog.csdn.net/qiaochao911/article/details/23440633 "收藏这段代码")

01. /\**
02. \* 消息集合
03. \*/
04. public interface MessageSet {
05. public MessageSet slice(long offset,long limit) throws IOException;//获取一个消息集合
06. public void write(GetCommand getCommand, SessionContext ctx);
07. public long append(ByteBuffer buff)throws IOException; //存储一个消息，这时候还没有存储到磁盘，需要调用flush方法才能保证存储到磁盘
08. public void flush()throws IOException; //提交到磁盘
09. public void read(final ByteBuffer bf,long offset) throws IOException;//读取消息
10. public void read(final ByteBuffer bf)throws IOException; //读取消息
11. public long getMessageCount();//该集合的消息数量
12. }

**\[java]** [view plain](http://blog.csdn.net/qiaochao911/article/details/23440633 "view plain")[copy](http://blog.csdn.net/qiaochao911/article/details/23440633 "copy")[![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/286558 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/286558/fork "派生到我的代码片")

 

01. /\**
02. * 消息集合
03. \*/
04. public interface MessageSet {
05. public MessageSet slice(long offset, long limit) throws IOException; //获取一个消息集合
06. public void write(GetCommand getCommand, SessionContext ctx);
07. public long append(ByteBuffer buff) throws IOException; //存储一个消息，这时候还没有存储到磁盘，需要调用flush方法才能保证存储到磁盘
08. public void flush() throws IOException; //提交到磁盘
09. public void read(final ByteBuffer bf, long offset) throws IOException; //读取消息
10. public void read(final ByteBuffer bf) throws IOException; //读取消息
11. public long getMessageCount();//该集合的消息数量
12. }

FileMessageSet实现了MessageSet接口和Closeable接口，实现Closeable接口主要是为了在文件关闭的时候确保文件通道关闭以及内容是否提交到磁盘

 

Java代码 [![复制代码](http://udukwilliam.iteye.com/images/icon_copy.gif)](http://udukwilliam.iteye.com/blog/1929253 "复制代码") [![收藏代码](http://udukwilliam.iteye.com/images/icon_star.png)![](http://udukwilliam.iteye.com/images/spinner.gif)](http://blog.csdn.net/qiaochao911/article/details/23440633 "收藏这段代码")

01. public void close()throws IOException {
02. if (!this.channel.isOpen()) {
03. return;
04. }
05. //保证在文件关闭前，将内容提交到磁盘，而不是在缓存中
06. if (this.mutable) {
07. this.flush();
08. }
09. //关闭文件通道
10. this.channel.close();
11. }

**\[java]** [view plain](http://blog.csdn.net/qiaochao911/article/details/23440633 "view plain")[copy](http://blog.csdn.net/qiaochao911/article/details/23440633 "copy")[![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/286558 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/286558/fork "派生到我的代码片")

 

01. public void close() throws IOException {
02. if (!this.channel.isOpen()) {
03. return;
04. }
05. //保证在文件关闭前，将内容提交到磁盘，而不是在缓存中
06. if (this.mutable) {
07. this.flush();
08. }
09. //关闭文件通道
10. this.channel.close();
11. }

下面让我们来具体分析一下FileMessageSet这个类，

Java代码 [![复制代码](http://udukwilliam.iteye.com/images/icon_copy.gif)](http://udukwilliam.iteye.com/blog/1929253 "复制代码") [![收藏代码](http://udukwilliam.iteye.com/images/icon_star.png)![](http://udukwilliam.iteye.com/images/spinner.gif)](http://blog.csdn.net/qiaochao911/article/details/23440633 "收藏这段代码")

001. public class FileMessageSetimplements MessageSet, Closeable {
002. ……
003. private final FileChannel channel;//对应的文件通道
004. private final AtomicLong messageCount;//内容数量
005. private final AtomicLong sizeInBytes;
006. private final AtomicLong highWaterMark;// 已经确保写入磁盘的水位
007. private finallong offset; // 镜像offset
008. private boolean mutable;  // 是否可变
009. public FileMessageSet(final FileChannel channel,final long offset,final long limit,finalboolean mutable)throws IOException {
010. this.channel = channel;
011. this.offset = offset;
012. this.messageCount = new AtomicLong(0);
013. this.sizeInBytes = new AtomicLong(0);
014. this.highWaterMark = new AtomicLong(0);
015. this.mutable = mutable;
016. if (mutable) {
017. final long startMs = System.currentTimeMillis();
018. final long truncated =this.recover();
019. if (this.messageCount.get() &gt;0) {
020. log.info("Recovery succeeded in " + (System.currentTimeMillis() - startMs) /1000 + " seconds. " + truncated +" bytes truncated.");
021. }
022. } else {
023. try {
024. this.sizeInBytes.set(Math.min(channel.size(), limit) - offset);
025. this.highWaterMark.set(this.sizeInBytes.get());
026. } catch (final Exception e) {
027. log.error("Set sizeInBytes error", e);
028. }
029. }
030. }
031. //注意FileMessageSet的mutable属性，如果mutable为true的时候，将会调用recover()方法，该方法主要是验证文件内容的完整性，后面会详细介绍，如果mutable为false的时候，表明该文件不可更改，这个时候磁盘水位和sizeInBytes的值均为文件大小。
032. ……
033. public long append(final ByteBuffer buf)throws IOException {
034. //如果mutable属性为false的时候，不允许追加消息在文件尾
035. if (!this.mutable) {
036. throw new UnsupportedOperationException("Immutable message set");
037. }
038. final long offset =this.sizeInBytes.get();
039. int sizeInBytes = 0;
040. while (buf.hasRemaining()) {
041. sizeInBytes += this.channel.write(buf);
042. }
043. //在这个时候并没有将内容写入磁盘，还在通道的缓存中，需要在适当的时候调用flush方法
044. //这个时候磁盘的水位是不更新的，只有在保证写入磁盘才会更新磁盘的水位信息
045. this.sizeInBytes.addAndGet(sizeInBytes); 、
046. this.messageCount.incrementAndGet();
047. return offset;
048. }
049. //提交到磁盘
050. public void flush()throws IOException {
051. this.channel.force(true);
052. this.highWaterMark.set(this.sizeInBytes.get());
053. }
054. ……
055. @Override
056. public MessageSet slice(finallong offset, finallong limit) throws IOException {
057. //返回消息集
058. return new FileMessageSet(this.channel, offset, limit,false);
059. }
060. static final Logger transferLog = LoggerFactory.getLogger("TransferLog");
061. @Override
062. public void read(final ByteBuffer bf,final long offset)throws IOException {
063. //读取内容
064. int size = 0;
065. while (bf.hasRemaining()) {
066. final int l =this.channel.read(bf, offset + size);
067. if (l &lt; 0) {
068. break;
069. }
070. size += l;
071. }
072. }
073. @Override
074. public void read(final ByteBuffer bf)throws IOException {
075. this.read(bf, this.offset);
076. }
077. //下面的write方法主要是提供zero拷贝
078. @Override
079. public void write(final GetCommand getCommand,final SessionContext ctx) {
080. final IoBuffer buf = this.makeHead(getCommand.getOpaque(),this.sizeInBytes.get());
081. // transfer to socket
082. this.tryToLogTransferInfo(getCommand, ctx.getConnection());
083. ctx.getConnection().transferFrom(buf, null,this.channel,this.offset,this.sizeInBytes.get());
084. }
085. public long write(final WritableByteChannel socketChanel)throws IOException {
086. try {
087. return this.getFileChannel().transferTo(this.offset,this.getSizeInBytes(), socketChanel);
088. } catch (final IOException e) {
089. // Check to see if the IOException is being thrown due to
090. // http://bugs.sun.com/bugdatabase/view\_bug.do?bug\_id=5103988
091. final String message = e.getMessage();
092. if (message != null && message.contains("temporarily unavailable")) {
093. return 0;
094. }
095. throw e;
096. }
097. }
098. ……
099. private staticboolean fastBoot = Boolean.valueOf(System.getProperty("meta.fast\_boot","false"));
100. private long recover()throws IOException {
101. //如果在System属性里设置了 meta.fast\_boot为true，表示快速启动，快速启动不检测文件是否损坏，不对内容进行校验
102. if (fastBoot) {
103. final long size =this.channel.size();
104. this.sizeInBytes.set(size);
105. this.highWaterMark.set(size);
106. this.messageCount.set(0);
107. this.channel.position(size);
108. return 0;
109. }
110. if (!this.mutable) {
111. throw new UnsupportedOperationException("Immutable message set");
112. }
113. final long len =this.channel.size();
114. final ByteBuffer buf = ByteBuffer.allocate(MessageUtils.HEADER\_LEN);
115. long validUpTo = 0L;
116. long next = 0L;
117. long msgCount = 0;
118. do {
119. next = this.validateMessage(buf, validUpTo, len);
120. if (next &gt;= 0) {
121. msgCount++;
122. validUpTo = next;
123. }
124. } while (next &gt;= 0);
125. this.channel.truncate(validUpTo);
126. this.sizeInBytes.set(validUpTo);
127. this.highWaterMark.set(validUpTo);
128. this.messageCount.set(msgCount);
129. this.channel.position(validUpTo);
130. return len - validUpTo;
131. }
132. 消息在磁盘上存储结构如下：
133. /*
134. \* 20个字节的头部 *
135. \* &lt;ul&gt;
136. \* &lt;li&gt;message length(4 bytes),including attribute and payload&lt;/li&gt;
137. \* &lt;li&gt;checksum(4 bytes)&lt;/li&gt;
138. \* &lt;li&gt;message id(8 bytes)&lt;/li&gt;
139. \* &lt;li&gt;message flag(4 bytes)&lt;/li&gt;
140. \* &lt;/ul&gt;
141. *  length长度的内容
142. \*/
143. //在存储之前将checksum的信息存入到磁盘，读取的时候再进行校验，比较前后的
144. //checksum是否一致，防止消息被篡改
145. private long validateMessage(final ByteBuffer buf,final long start,final long len)throwsIOException {
146. buf.rewind();
147. long read = this.channel.read(buf);
148. if (read &lt; MessageUtils.HEADER\_LEN) {
149. return -1;
150. }
151. buf.flip();
152. final int messageLen = buf.getInt();
153. final long next = start + MessageUtils.HEADER\_LEN + messageLen;
154. if (next &gt; len) {
155. return -1;
156. }
157. final int checksum = buf.getInt();
158. if (messageLen &lt; 0) {
159. // 数据损坏
160. return -1;
161. }
162. final ByteBuffer messageBuffer = ByteBuffer.allocate(messageLen);
163. //        long curr = start + MessageUtils.HEADER\_LEN;
164. while (messageBuffer.hasRemaining()) {
165. read = this.channel.read(messageBuffer);
166. if (read &lt; 0) {
167. throw new IOException("文件在recover过程中被修改");
168. }
169. //            curr += read;
170. }
171. if (CheckSum.crc32(messageBuffer.array()) != checksum) {
172. //采用crc32对内容进行校验是否一致
173. return -1;
174. } else {
175. return next;
176. }
177. }

**\[java]** [view plain](http://blog.csdn.net/qiaochao911/article/details/23440633 "view plain")[copy](http://blog.csdn.net/qiaochao911/article/details/23440633 "copy")[![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/286558 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/286558/fork "派生到我的代码片")

 

001. public class FileMessageSet implements MessageSet, Closeable {
002. ……
003. private final FileChannel channel; //对应的文件通道
004. private final AtomicLong messageCount; //内容数量
005. private final AtomicLong sizeInBytes;
006. private final AtomicLong highWaterMark; // 已经确保写入磁盘的水位
007. private final long offset; // 镜像offset
008. private boolean mutable;   // 是否可变
009. public FileMessageSet(final FileChannel channel, final long offset, final long limit, final boolean mutable) throws IOException {
010. this.channel = channel;
011. this.offset = offset;
012. this.messageCount = new AtomicLong(0);
013. this.sizeInBytes = new AtomicLong(0);
014. this.highWaterMark = new AtomicLong(0);
015. this.mutable = mutable;
016. if (mutable) {
017. final long startMs = System.currentTimeMillis();
018. final long truncated = this.recover();
019. if (this.messageCount.get() &gt; 0) {
020. log.info("Recovery succeeded in " + (System.currentTimeMillis() - startMs) / 1000 + " seconds. " + truncated + " bytes truncated.");
021. }
022. } else {
023. try {
024. this.sizeInBytes.set(Math.min(channel.size(), limit) - offset);
025. this.highWaterMark.set(this.sizeInBytes.get());
026. } catch (final Exception e) {
027. log.error("Set sizeInBytes error", e);
028. }
029. }
030. }
031. //注意FileMessageSet的mutable属性，如果mutable为true的时候，将会调用recover()方法，该方法主要是验证文件内容的完整性，后面会详细介绍，如果mutable为false的时候，表明该文件不可更改，这个时候磁盘水位和sizeInBytes的值均为文件大小。
032. ……
033. public long append(final ByteBuffer buf) throws IOException {
034. //如果mutable属性为false的时候，不允许追加消息在文件尾
035. if (!this.mutable) {
036. throw new UnsupportedOperationException("Immutable message set");
037. }
038. final long offset = this.sizeInBytes.get();
039. int sizeInBytes = 0;
040. while (buf.hasRemaining()) {
041. sizeInBytes += this.channel.write(buf);
042. }
043. //在这个时候并没有将内容写入磁盘，还在通道的缓存中，需要在适当的时候调用flush方法
044. //这个时候磁盘的水位是不更新的，只有在保证写入磁盘才会更新磁盘的水位信息
045. this.sizeInBytes.addAndGet(sizeInBytes); 、
046. this.messageCount.incrementAndGet();
047. return offset;
048. }
049. //提交到磁盘
050. public void flush() throws IOException {
051. this.channel.force(true);
052. this.highWaterMark.set(this.sizeInBytes.get());
053. }
054. ……
055. @Override
056. public MessageSet slice(final long offset, final long limit) throws IOException {
057. //返回消息集
058. return new FileMessageSet(this.channel, offset, limit, false);
059. }
060. static final Logger transferLog = LoggerFactory.getLogger("TransferLog");
061. @Override
062. public void read(final ByteBuffer bf, final long offset) throws IOException {
063. //读取内容
064. int size = 0;
065. while (bf.hasRemaining()) {
066. final int l = this.channel.read(bf, offset + size);
067. if (l &lt; 0) {
068. break;
069. }
070. size += l;
071. }
072. }
073. @Override
074. public void read(final ByteBuffer bf) throws IOException {
075. this.read(bf, this.offset);
076. }
077. //下面的write方法主要是提供zero拷贝
078. @Override
079. public void write(final GetCommand getCommand, final SessionContext ctx) {
080. final IoBuffer buf = this.makeHead(getCommand.getOpaque(), this.sizeInBytes.get());
081. // transfer to socket
082. this.tryToLogTransferInfo(getCommand, ctx.getConnection());
083. ctx.getConnection().transferFrom(buf, null, this.channel, this.offset, this.sizeInBytes.get());
084. }
085. public long write(final WritableByteChannel socketChanel) throws IOException {
086. try {
087. return this.getFileChannel().transferTo(this.offset, this.getSizeInBytes(), socketChanel);
088. } catch (final IOException e) {
089. // Check to see if the IOException is being thrown due to
090. // http://bugs.sun.com/bugdatabase/view\_bug.do?bug\_id=5103988
091. final String message = e.getMessage();
092. if (message != null && message.contains("temporarily unavailable")) {
093. return 0;
094. }
095. throw e;
096. }
097. }
098. ……
099. private static boolean fastBoot = Boolean.valueOf(System.getProperty("meta.fast\_boot", "false"));
100. private long recover() throws IOException {
101. //如果在System属性里设置了 meta.fast\_boot为true，表示快速启动，快速启动不检测文件是否损坏，不对内容进行校验
102. if (fastBoot) {
103. final long size = this.channel.size();
104. this.sizeInBytes.set(size);
105. this.highWaterMark.set(size);
106. this.messageCount.set(0);
107. this.channel.position(size);
108. return 0;
109. }
110. if (!this.mutable) {
111. throw new UnsupportedOperationException("Immutable message set");
112. }
113. final long len = this.channel.size();
114. final ByteBuffer buf = ByteBuffer.allocate(MessageUtils.HEADER\_LEN);
115. long validUpTo = 0L;
116. long next = 0L;
117. long msgCount = 0;
118. do {
119. next = this.validateMessage(buf, validUpTo, len);
120. if (next &gt;= 0) {
121. msgCount++;
122. validUpTo = next;
123. }
124. } while (next &gt;= 0);
125. this.channel.truncate(validUpTo);
126. this.sizeInBytes.set(validUpTo);
127. this.highWaterMark.set(validUpTo);
128. this.messageCount.set(msgCount);
129. this.channel.position(validUpTo);
130. return len - validUpTo;
131. }
132. 消息在磁盘上存储结构如下：
133. /*
134. * 20个字节的头部 *
135. * &lt;ul&gt;
136. * &lt;li&gt;message length(4 bytes),including attribute and payload&lt;/li&gt;
137. * &lt;li&gt;checksum(4 bytes)&lt;/li&gt;
138. * &lt;li&gt;message id(8 bytes)&lt;/li&gt;
139. * &lt;li&gt;message flag(4 bytes)&lt;/li&gt;
140. * &lt;/ul&gt;
141. *  length长度的内容
142. \*/
143. //在存储之前将checksum的信息存入到磁盘，读取的时候再进行校验，比较前后的
144. //checksum是否一致，防止消息被篡改
145. private long validateMessage(final ByteBuffer buf, final long start, final long len) throws IOException {
146. buf.rewind();
147. long read = this.channel.read(buf);
148. if (read &lt; MessageUtils.HEADER\_LEN) {
149. return -1;
150. }
151. buf.flip();
152. final int messageLen = buf.getInt();
153. final long next = start + MessageUtils.HEADER\_LEN + messageLen;
154. if (next &gt; len) {
155. return -1;
156. }
157. final int checksum = buf.getInt();
158. if (messageLen &lt; 0) {
159. // 数据损坏
160. return -1;
161. }
162. final ByteBuffer messageBuffer = ByteBuffer.allocate(messageLen);
163. //        long curr = start + MessageUtils.HEADER\_LEN;
164. while (messageBuffer.hasRemaining()) {
165. read = this.channel.read(messageBuffer);
166. if (read &lt; 0) {
167. throw new IOException("文件在recover过程中被修改");
168. }
169. //            curr += read;
170. }
171. if (CheckSum.crc32(messageBuffer.array()) != checksum) {
172. //采用crc32对内容进行校验是否一致
173. return -1;
174. } else {
175. return next;
176. }
177. }

    FileMessageSet是MetaQ 服务器端存储的一个元素，代表了对一个文件的读写操作，能够对文件内容进行完整性和一致性校验，并能提供统计数据，接下来要介绍的是通过MessageStore怎样的组合将一个个的FileMessageSet，单纯的讲，MetaQ的存储非常值得借鉴。