---
title: "MetaQ技术内幕——源码分析(三)"
author: "wbj0110"
date: "2014-05-31T12:45:13Z"
tags: ["metaq"]
categories: ["编程语言"]
slug: "metaq"
draft: false
lastmod: "2014-05-30T16:19:51Z"
id: 2074316
url: "https://soledede.iteye.com/blog/2074316"
---

前面忘了先介绍一下Broker消息存储的组织方式，我们前面知道了一条消息属于某个Topic下的某个分区，消息存储的组织方式是按照此方式进行组织的，结构图如下：

![](http://dl2.iteye.com/upload/attachment/0088/5646/f5044841-53b6-3801-bbb8-4d153a8eb7eb.jpg)

 

所以对于每个Topic而言，分区是最小的元素，对外API主要由MessageStore提供，一个MessageStore实例代表一个分区的实例，分区存储具体的内容。在MetaQ中，分区的存储采用的多文件的方式进行组合，即MessageStore由多个FileMessageSet组成，而FileMessageSet在MessageStore被包装成Segment，代码如下（MessageStore是值得好好分析的一个类）：

 

 

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

1. public class MessageStore extends Thread implements Closeable {
2. …….
3. }

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

 

1. public class MessageStore extends Thread implements Closeable {
2. …….
3. }

MessageStore继承了Thread类，继承该类主要是为了实现异步写入方式

 

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

01. public MessageStore(final String topic, final int partition, final MetaConfig metaConfig,
02. final DeletePolicy deletePolicy, final long offsetIfCreate) throws IOException {
03. this.metaConfig = metaConfig; //全局配置信息
04. this.topic = topic; //当前主题
05. final TopicConfig topicConfig = this.metaConfig.getTopicConfig(this.topic);
06. String dataPath = metaConfig.getDataPath(); //当前分区的存储路径
07. if (topicConfig != null) {
08. dataPath = topicConfig.getDataPath();
09. }
10. final File parentDir = new File(dataPath);
11. this.checkDir(parentDir); //检测父目录是否存在
12. this.partitionDir = new File(dataPath + File.separator + topic + "-" + partition);
13. this.checkDir(this.partitionDir);
14. // this.topic = topic;
15. this.partition = partition; //当前分区
16. this.unflushed = new AtomicInteger(0); //未提交的消息数
17. this.lastFlushTime = new AtomicLong(SystemTimer.currentTimeMillis()); //最后一次提交时间
18. this.unflushThreshold = topicConfig.getUnflushThreshold(); //最大允许的未flush消息数，超过此值将强制force到磁盘，默认1000
19. this.deletePolicy = deletePolicy;  //由于是多文件的存储方式，消费过的消息或过期消息需要删除从而腾出空间给新消息的，默认提供归档和过期删除的方式
20. // Make a copy to avoid getting it again and again.
21. this.maxTransferSize = metaConfig.getMaxTransferSize();
22. //启动异步写入的时候，消息提交到磁盘的size配置，同时也是配置组写入时，消息最大长度的控制参数，如果消息长度大于该参数，则会同步写入
23. this.maxTransferSize = this.maxTransferSize &gt; ONE\_M\_BYTES ? ONE\_M\_BYTES :this.maxTransferSize;
24. // Check directory and load exists segments.
25. this.checkDir(this.partitionDir);
26. this.loadSegments(offsetIfCreate);
27. if (this.useGroupCommit()) {
28. this.start();
29. }
30. }

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

 

01. public MessageStore(final String topic, final int partition, final MetaConfig metaConfig,
02. final DeletePolicy deletePolicy, final long offsetIfCreate) throws IOException {
03. this.metaConfig = metaConfig; //全局配置信息
04. this.topic = topic; //当前主题
05. final TopicConfig topicConfig = this.metaConfig.getTopicConfig(this.topic);
06. String dataPath = metaConfig.getDataPath(); //当前分区的存储路径
07. if (topicConfig != null) {
08. dataPath = topicConfig.getDataPath();
09. }
10. final File parentDir = new File(dataPath);
11. this.checkDir(parentDir); //检测父目录是否存在
12. this.partitionDir = new File(dataPath + File.separator + topic + "-" + partition);
13. this.checkDir(this.partitionDir);
14. // this.topic = topic;
15. this.partition = partition; //当前分区
16. this.unflushed = new AtomicInteger(0); //未提交的消息数
17. this.lastFlushTime = new AtomicLong(SystemTimer.currentTimeMillis()); //最后一次提交时间
18. this.unflushThreshold = topicConfig.getUnflushThreshold(); //最大允许的未flush消息数，超过此值将强制force到磁盘，默认1000
19. this.deletePolicy = deletePolicy;  //由于是多文件的存储方式，消费过的消息或过期消息需要删除从而腾出空间给新消息的，默认提供归档和过期删除的方式
20. // Make a copy to avoid getting it again and again.
21. this.maxTransferSize = metaConfig.getMaxTransferSize();
22. //启动异步写入的时候，消息提交到磁盘的size配置，同时也是配置组写入时，消息最大长度的控制参数，如果消息长度大于该参数，则会同步写入
23. this.maxTransferSize = this.maxTransferSize &gt; ONE\_M\_BYTES ? ONE\_M\_BYTES : this.maxTransferSize;
24. // Check directory and load exists segments.
25. this.checkDir(this.partitionDir);
26. this.loadSegments(offsetIfCreate);
27. if (this.useGroupCommit()) {
28. this.start();
29. }
30. }

首先是获取配置信息，其次由于MessageStore采用的多文件存储方,所以要检查父目录的存在，最后则是加载校验已有数据，如果配置了异步写入，则启动异步写入线程（如果unflushThreshold&lt;= 0，则认为启动异步写入的方式）

 

我们发现在构造方法的倒数第3行调用了loadSegments()方法去加载校验文件，看看该方法到底做了些什么事情

 

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

01. private void loadSegments(final long offsetIfCreate) throws IOException {
02. final List&lt;Segment&gt; accum = new ArrayList&lt;Segment&gt;();
03. final File\[] ls = this.partitionDir.listFiles();
04. if (ls != null) {
05. //遍历目录下的所有.meta后缀的数据文件，将所有文件都变为不可变的文件
06. for (final File file : ls) {
07. if (file.isFile() && file.toString().endsWith(FILE\_SUFFIX)) {
08. if (!file.canRead()) {
09. throw new IOException("Could not read file " + file);
10. }
11. final String filename = file.getName();
12. final long start = Long.parseLong(filename.substring(0, filename.length() - FILE\_SUFFIX.length()));
13. // 先作为不可变的加载进来
14. accum.add(new Segment(start, file, false));
15. }
16. }
17. }
18. if (accum.size() == 0) {
19. // 没有可用的文件，创建一个，索引从offsetIfCreate开始
20. final File newFile = new File(this.partitionDir,this.nameFromOffset(offsetIfCreate));
21. accum.add(new Segment(offsetIfCreate, newFile));
22. } else {
23. // 至少有一个文件，校验并按照start升序排序
24. Collections.sort(accum, new Comparator&lt;Segment&gt;() {
25. @Override
26. public int compare(final Segment o1, final Segment o2) {
27. if (o1.start == o2.start) {
28. return 0;
29. } else if (o1.start &gt; o2.start) {
30. return 1;
31. } else {
32. return -1;
33. }
34. }
35. });
36. // 校验文件，是否前后衔接，如果不是，则认为数据文件被破坏或者篡改，抛出异常
37. this.validateSegments(accum);
38. // 最后一个文件修改为可变
39. final Segment last = accum.remove(accum.size() - 1);
40. last.fileMessageSet.close();
41. log.info("Loading the last segment in mutable mode and running recover on " + last.file.getAbsolutePath());
42. final Segment mutable = new Segment(last.start, last.file);
43. accum.add(mutable);
44. log.info("Loaded " + accum.size() + " segments...");
45. }
46. this.segments = new SegmentList(accum.toArray(new Segment\[accum.size()]));
47. //多个segmentg通过SegmentList组织起来，SegmentList能保证在并发访问下的删除、添加保持一致性，SegmentList没有采用java的关键字 synchronized进行同步，而是使用类似cvs原语的方式进行同步访问（因为绝大部分情况下并没有并发问题，可以极大的提高效率），该类比较简单就不再分析
48. }

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

 

01. private void loadSegments(final long offsetIfCreate) throws IOException {
02. final List&lt;Segment&gt; accum = new ArrayList&lt;Segment&gt;();
03. final File\[] ls = this.partitionDir.listFiles();
04. if (ls != null) {
05. //遍历目录下的所有.meta后缀的数据文件，将所有文件都变为不可变的文件
06. for (final File file : ls) {
07. if (file.isFile() && file.toString().endsWith(FILE\_SUFFIX)) {
08. if (!file.canRead()) {
09. throw new IOException("Could not read file " + file);
10. }
11. final String filename = file.getName();
12. final long start = Long.parseLong(filename.substring(0, filename.length() - FILE\_SUFFIX.length()));
13. // 先作为不可变的加载进来
14. accum.add(new Segment(start, file, false));
15. }
16. }
17. }
18. if (accum.size() == 0) {
19. // 没有可用的文件，创建一个，索引从offsetIfCreate开始
20. final File newFile = new File(this.partitionDir, this.nameFromOffset(offsetIfCreate));
21. accum.add(new Segment(offsetIfCreate, newFile));
22. } else {
23. // 至少有一个文件，校验并按照start升序排序
24. Collections.sort(accum, new Comparator&lt;Segment&gt;() {
25. @Override
26. public int compare(final Segment o1, final Segment o2) {
27. if (o1.start == o2.start) {
28. return 0;
29. } else if (o1.start &gt; o2.start) {
30. return 1;
31. } else {
32. return -1;
33. }
34. }
35. });
36. // 校验文件，是否前后衔接，如果不是，则认为数据文件被破坏或者篡改，抛出异常
37. this.validateSegments(accum);
38. // 最后一个文件修改为可变
39. final Segment last = accum.remove(accum.size() - 1);
40. last.fileMessageSet.close();
41. log.info("Loading the last segment in mutable mode and running recover on " + last.file.getAbsolutePath());
42. final Segment mutable = new Segment(last.start, last.file);
43. accum.add(mutable);
44. log.info("Loaded " + accum.size() + " segments...");
45. }
46. this.segments = new SegmentList(accum.toArray(new Segment\[accum.size()]));
47. //多个segmentg通过SegmentList组织起来，SegmentList能保证在并发访问下的删除、添加保持一致性，SegmentList没有采用java的关键字 synchronized进行同步，而是使用类似cvs原语的方式进行同步访问（因为绝大部分情况下并没有并发问题，可以极大的提高效率），该类比较简单就不再分析
48. }

 

MessageStore采用Segment方式组织存储，Segment包装了FileMessageSet，由FileMessageSet进行读写，MessageStore并将多个Segment进行前后衔接，衔接方式为：第一个Segment对应的消息文件命名为0.meta，第二个则命名为第一个文件的开始位置+第一个Segment的大小，图示如下(假设现在每个文件大小都为1024byte)：

![](http://dl2.iteye.com/upload/attachment/0088/5624/57892fca-a797-3772-9be2-d21d75371a6b.jpg)

为什么要这样进行设计呢，主要是为了提高查询效率。MessageStore将最后一个Segment变为可变Segment，因为最后一个Segment相当于文件尾，消息是有先后顺序的，必须将消息添加到最后一个Segment上。

关注validateSegments()方法做了些什么事情

 

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

01. private void validateSegments(final List&lt;Segment&gt; segments) {
02. //验证按升序排序的Segment是否前后衔接，确保文件没有被篡改和破坏(这里的验证是比较简单的验证，消息内容的验证在FileMessageSet中，通过比较checksum进行验证，在前面的篇幅中介绍过，这两种方式结合可以在范围上从大到小进行验证，保证内容基本不被破坏和篡改)
03. this.writeLock.lock();
04. try {
05. for (int i = 0; i &lt; segments.size() - 1; i++) {
06. final Segment curr = segments.get(i);
07. final Segment next = segments.get(i + 1);
08. if (curr.start + curr.size() != next.start) {
09. throw new IllegalStateException("The following segments don't validate: "
10. \+ curr.file.getAbsolutePath() + ", " + next.file.getAbsolutePath());
11. }
12. }
13. } finally {
14. this.writeLock.unlock();
15. }
16. }

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

 

01. private void validateSegments(final List&lt;Segment&gt; segments) {
02. //验证按升序排序的Segment是否前后衔接，确保文件没有被篡改和破坏(这里的验证是比较简单的验证，消息内容的验证在FileMessageSet中，通过比较checksum进行验证，在前面的篇幅中介绍过，这两种方式结合可以在范围上从大到小进行验证，保证内容基本不被破坏和篡改)
03. this.writeLock.lock();
04. try {
05. for (int i = 0; i &lt; segments.size() - 1; i++) {
06. final Segment curr = segments.get(i);
07. final Segment next = segments.get(i + 1);
08. if (curr.start + curr.size() != next.start) {
09. throw new IllegalStateException("The following segments don't validate: "
10. + curr.file.getAbsolutePath() + ", " + next.file.getAbsolutePath());
11. }
12. }
13. } finally {
14. this.writeLock.unlock();
15. }
16. }

 

 

   ITEye整理格式好麻烦，下面的代码分析直接在代码中分析

 

 

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

001. //添加消息的方式有两种，同步和异步
002. public void append(final long msgId, final PutCommand req, final AppendCallback cb) {
003. //首先将内容包装成前面介绍过的消息存储格式
004. this.appendBuffer(MessageUtils.makeMessageBuffer(msgId, req), cb);
005. }
006. //异步写入的包装类
007. private static class WriteRequest {
008. public final ByteBuffer buf;
009. public final AppendCallback cb;
010. public Location result;
011. public WriteRequest(final ByteBuffer buf, final AppendCallback cb) {
012. super();
013. this.buf = buf;
014. this.cb = cb;
015. }
016. }
017. //这里比较好的设计是采用回调的方式来，对于异步写入实现就变得非常容易
018. //AppendCallback返回的是消息成功写入的位置Location(起始位置和消息长度)，该Location并不是相对于当前Segment的开始位置0，而是相对于当前Segment给定的值(对应文件命名值即为给定的值)，以后查询消息的时候直接使用该位置就可以快速定位到消息写入到哪个文件
019. //这也就是为什么文件名的命名采用前后衔接的方式，这也通过2分查找可以快速定位消息的位置
020. private void appendBuffer(final ByteBuffer buffer, final AppendCallback cb) {
021. if (this.closed) {
022. throw new IllegalStateException("Closed MessageStore.");
023. }
024. //如果启动异步写入并且消息长度小于一次提交的最大值maxTransferSize，则将该消息放入异步写入队列
025. if (this.useGroupCommit() && buffer.remaining() &lt; this.maxTransferSize) {
026. this.bufferQueue.offer(new WriteRequest(buffer, cb));
027. } else {
028. Location location = null;
029. final int remainning = buffer.remaining();
030. this.writeLock.lock();
031. try {
032. final Segment cur = this.segments.last();
033. final long offset = cur.start + cur.fileMessageSet.append(buffer);
034. this.mayBeFlush(1);
035. this.mayBeRoll();
036. location = Location.create(offset, remainning);
037. } catch (final IOException e) {
038. log.error("Append file failed", e);
039. location = Location.InvalidLocaltion;
040. } finally {
041. this.writeLock.unlock();
042. if (cb != null) {
043. cb.appendComplete(location);
044. }
045. //调用回调方法，数据写入文件缓存
046. }
047. }
048. }
049. ……
050. //判断是否启用异步写入，如果设置为unflushThreshold &lt;=0的数字，则认为启动异步写入；如果设置为unflushThreshold =1，则是同步写入，即每写入一个消息都会提交到磁盘；如果unflushThreshold&gt;0，则是依赖组提交或者是超时提交
051. private boolean useGroupCommit() {
052. return this.unflushThreshold &lt;= 0;
053. }
054. @Override
055. public void run() {
056. // 等待force的队列
057. final LinkedList&lt;WriteRequest&gt; toFlush = new LinkedList&lt;WriteRequest&gt;();
058. WriteRequest req = null;
059. long lastFlushPos = 0;
060. Segment last = null;
061. //存储没有关闭并且线程没有被中断
062. while (!this.closed && !Thread.currentThread().isInterrupted()) {
063. try {
064. if (last == null) {
065. //获取最后的一个segment，将消息写入最后segment对应的文件
066. last = this.segments.last();
067. lastFlushPos = last.fileMessageSet.highWaterMark();
068. }
069. if (req == null) {
070. //如果等待提交到磁盘的队列toFlush为空，则两种可能：一、刚刚提交完，列表为空；二、等待写入消息的队列为空，如果判断toFlush，则调用bufferQueue.take()方法，可以阻塞住队列，而如果toFlush不为空，则调用bufferQueue.poll，这是提高性能的一种做法。
071. if (toFlush.isEmpty()) {
072. req = this.bufferQueue.take();
073. } else {
074. req = this.bufferQueue.poll();
075. //如果当前请求为空，表明等待写入的消息已经没有了，这时候文件缓存中的消息需要提交到磁盘，防止消息丢失；或者如果已经写入文件的大小大于maxTransferSize，则提交到磁盘
076. //这里需要注意的是，会出现这样一种情况，刚好最后一个segment的文件快满了，这时候是不会roll出一个新的segment写入消息的，而是直接追加到原来的segment尾部，可能导致segment对应的文件大小大于配置的单个segment大小
077. if (req == null || last.fileMessageSet.getSizeInBytes() &gt; lastFlushPos + this.maxTransferSize) {
078. // 强制force，确保内容保存到磁盘
079. last.fileMessageSet.flush();
080. lastFlushPos = last.fileMessageSet.highWaterMark();
081. // 通知回调
082. //异步写入比组写入可靠，因为异步写入一定是提交到磁盘的时候才进行回调的，而组写入如果依赖组提交的方式，则可能会丢失数据，因为组写入在消息写入到文件缓存的时候就进行回调了(除非设置unflushThreshold=1)
083. for (final WriteRequest request : toFlush) {
084. request.cb.appendComplete(request.result);
085. }
086. toFlush.clear();
087. // 是否需要roll
088. this.mayBeRoll();
089. // 如果切换文件，重新获取last
090. if (this.segments.last() != last) {
091. last = null;
092. }
093. continue;
094. }
095. }
096. }
097. if (req == null) {
098. continue;
099. }
100. //写入文件，并计算写入位置
101. final int remainning = req.buf.remaining();
102. //写入位置为：当前segment给定的值 + 加上文件已有的长度
103. final long offset = last.start + last.fileMessageSet.append(req.buf);
104. req.result = Location.create(offset, remainning);
105. if (req.cb != null) {
106. toFlush.add(req);
107. }
108. req = null;
109. } catch (final IOException e) {
110. log.error("Append message failed,\*critical error\*,the group commit thread would be terminated.", e);
111. // TODO io异常没办法处理了，简单跳出?
112. break;
113. } catch (final InterruptedException e) {
114. // ignore
115. }
116. }
117. // terminated
118. //关闭store 前，将等待写入队列中的剩余消息写入最后一个文件，这时候如果最后一个Segment满了也不会roll出新的Segment，持续的将消息写入到最后一个Segment，所以这时候也会发生Segment的size大于配置的size的情况
119. try {
120. for (WriteRequest request : this.bufferQueue) {
121. final int remainning = request.buf.remaining();
122. final long offset = last.start + last.fileMessageSet.append(request.buf);
123. if (request.cb != null) {
124. request.cb.appendComplete(Location.create(offset, remainning));
125. }
126. }
127. this.bufferQueue.clear();
128. } catch (IOException e) {
129. log.error("Append message failed", e);
130. }
131. }
132. ……
133. //Append多个消息，返回写入的位置
134. public void append(final List&lt;Long&gt; msgIds, final List&lt;PutCommand&gt; putCmds, finalAppendCallback cb) {
135. this.appendBuffer(MessageUtils.makeMessageBuffer(msgIds, putCmds), cb);
136. }
137. /\**
138. \* 重放事务操作，如果消息没有存储成功，则重新存储，并返回新的位置
139. \*/
140. public void replayAppend(final long offset, final int length, final int checksum,final List&lt;Long&gt; msgIds,
141. final List&lt;PutCommand&gt; reqs, final AppendCallback cb) throws IOException {
142. //如果消息没有存储，则重新存储，写到最后一个Segment尾部
143. final Segment segment = this.findSegment(this.segments.view(), offset);
144. if (segment == null) {
145. this.append(msgIds, reqs, cb);
146. } else {
147. final MessageSet messageSet = segment.fileMessageSet.slice(offset - segment.start, offset - segment.start + length);
148. final ByteBuffer buf = ByteBuffer.allocate(length);
149. messageSet.read(buf, offset - segment.start);
150. buf.flip();
151. final byte\[] bytes = new byte\[buf.remaining()];
152. buf.get(bytes);
153. // 这个校验和是整个消息的校验和，这跟message的校验和不一样，注意区分
154. final int checkSumInDisk = CheckSum.crc32(bytes);
155. // 没有存入，则重新存储
156. if (checksum != checkSumInDisk) {
157. this.append(msgIds, reqs, cb);
158. } else {
159. // 正常存储了消息，无需处理
160. if (cb != null) {
161. this.notifyCallback(cb, null);
162. }
163. }
164. }
165. }
166. //判断是否需要roll，如果当前 messagestore最后一个segment的size&gt;=配置的segment size，则产生新的segment，并将新的segment作为最后一个segment，原来最后的segment提交一次，并将mutable设置为false
167. private void mayBeRoll() throws IOException {
168. if (this.segments.last().fileMessageSet.getSizeInBytes() &gt;=this.metaConfig.getMaxSegmentSize()) {
169. this.roll();
170. }
171. }
172. String nameFromOffset(final long offset) {
173. final NumberFormat nf = NumberFormat.getInstance();
174. nf.setMinimumIntegerDigits(20);
175. nf.setMaximumFractionDigits(0);
176. nf.setGroupingUsed(false);
177. return nf.format(offset) + FILE\_SUFFIX;
178. }
179. private long nextAppendOffset() throws IOException {
180. final Segment last = this.segments.last();
181. last.fileMessageSet.flush();
182. return last.start + last.size();
183. }
184. private void roll() throws IOException {
185. final long newOffset = this.nextAppendOffset();
186. //新的segment对应的存储文件的命名为原来最后一个segment的起始位置 + segment的size
187. final File newFile = new File(this.partitionDir, this.nameFromOffset(newOffset));
188. this.segments.last().fileMessageSet.flush();
189. this.segments.last().fileMessageSet.setMutable(false);
190. this.segments.append(new Segment(newOffset, newFile));
191. }
192. //判断是否需要消息提交到磁盘，判断的条件有两个，如果达到组提交的条件或者达到间隔的提交时间
193. private void mayBeFlush(final int numOfMessages) throws IOException {
194. if (this.unflushed.addAndGet(numOfMessages) &gt;this.metaConfig.getTopicConfig(this.topic).getUnflushThreshold()
195. || SystemTimer.currentTimeMillis() - this.lastFlushTime.get() &gt;this.metaConfig.getTopicConfig(this.topic).getUnflushInterval()) {
196. this.flush0();
197. }
198. }
199. //提交到磁盘
200. public void flush() throws IOException {
201. this.writeLock.lock();
202. try {
203. this.flush0();
204. } finally {
205. this.writeLock.unlock();
206. }
207. }
208. private void flush0() throws IOException {
209. if (this.useGroupCommit()) {
210. return;
211. }
212. //由于只有最后一个segment是可变，即可写入消息的，所以只需要提交最后一个segment的消息
213. this.segments.last().fileMessageSet.flush();
214. this.unflushed.set(0);
215. this.lastFlushTime.set(SystemTimer.currentTimeMillis());
216. }
217. @Override
218. public void close() throws IOException {
219. this.closed = true;
220. this.interrupt();
221. //等待子线程完成写完异步队列中剩余未写的消息
222. try {
223. this.join(500);
224. } catch (InterruptedException e) {
225. Thread.currentThread().interrupt();
226. }
227. //关闭segment，保证内容都已经提交到磁盘
228. for (final Segment segment : this.segments.view()) {
229. segment.fileMessageSet.close();
230. }
231. }
232. //返回segment的信息，主要包括segment的开始位置以及 segment 的size
233. public List&lt;SegmentInfo&gt; getSegmentInfos() {
234. final List&lt;SegmentInfo&gt; rt = new ArrayList&lt;SegmentInfo&gt;();
235. for (final Segment seg : this.segments.view()) {
236. rt.add(new SegmentInfo(seg.start, seg.size()));
237. }
238. return rt;
239. }
240. /\**
241. \* 返回当前最大可读的offset
242. \*/
243. //需要注意的是，在文件缓存中的消息是不可读的，可以通过getSizeInBytes（）方法来判断还有多少内容还在文件缓存中，getSizeInBytes()方法返回的值是包括所有在磁盘和缓存中的size
244. public long getMaxOffset() {
245. final Segment last = this.segments.last();
246. if (last != null) {
247. return last.start + last.size();
248. } else {
249. return 0;
250. }
251. }
252. /\**
253. \* 返回当前最小可读的offset
254. \*/
255. public long getMinOffset() {
256. Segment first = this.segments.first();
257. if (first != null) {
258. return first.start;
259. } else {
260. return 0;
261. }
262. }
263. /\**
264. \* 根据offset和maxSize返回所在MessageSet, 当offset超过最大offset的时候返回null，
265. \* 当offset小于最小offset的时候抛出ArrayIndexOutOfBounds异常
266. \*/
267. //代码的注释以及清楚的解析了作用
268. public MessageSet slice(final long offset, final int maxSize) throws IOException {
269. final Segment segment = this.findSegment(this.segments.view(), offset);
270. if (segment == null) {
271. return null;
272. } else {
273. return segment.fileMessageSet.slice(offset - segment.start, offset - segment.start + maxSize);
274. }
275. }
276. /\**
277. \* 根据offset查找文件,如果超过尾部，则返回null，如果在头部之前，则抛出ArrayIndexOutOfBoundsException
278. \*/
279. //指定位置找到对应的segment，由于前面的文件组织方式，所以这里可以采用2分查找的方式，
280. //效率很高
281. Segment findSegment(final Segment\[] segments, final long offset) {
282. if (segments == null || segments.length &lt; 1) {
283. return null;
284. }
285. // 老的数据不存在，返回最近最老的数据
286. final Segment last = segments\[segments.length - 1];
287. // 在头部以前，抛出异常
288. if (offset &lt; segments\[0].start) {
289. throw new ArrayIndexOutOfBoundsException();
290. }
291. // 刚好在尾部或者超出范围，返回null
292. if (offset &gt;= last.start + last.size()) {
293. return null;
294. }
295. // 根据offset二分查找
296. int low = 0;
297. int high = segments.length - 1;
298. while (low &lt;= high) {
299. final int mid = high + low &gt;&gt;&gt; 1;
300. final Segment found = segments\[mid];
301. if (found.contains(offset)) {
302. return found;
303. } else if (offset &lt; found.start) {
304. high = mid - 1;
305. } else {
306. low = mid + 1;
307. }
308. }
309. return null;
310. }

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

 

001. //添加消息的方式有两种，同步和异步
002. public void append(final long msgId, final PutCommand req, final AppendCallback cb) {
003. //首先将内容包装成前面介绍过的消息存储格式
004. this.appendBuffer(MessageUtils.makeMessageBuffer(msgId, req), cb);
005. }
006. //异步写入的包装类
007. private static class WriteRequest {
008. public final ByteBuffer buf;
009. public final AppendCallback cb;
010. public Location result;
011. public WriteRequest(final ByteBuffer buf, final AppendCallback cb) {
012. super();
013. this.buf = buf;
014. this.cb = cb;
015. }
016. }
017. //这里比较好的设计是采用回调的方式来，对于异步写入实现就变得非常容易
018. //AppendCallback返回的是消息成功写入的位置Location(起始位置和消息长度)，该Location并不是相对于当前Segment的开始位置0，而是相对于当前Segment给定的值(对应文件命名值即为给定的值)，以后查询消息的时候直接使用该位置就可以快速定位到消息写入到哪个文件
019. //这也就是为什么文件名的命名采用前后衔接的方式，这也通过2分查找可以快速定位消息的位置
020. private void appendBuffer(final ByteBuffer buffer, final AppendCallback cb) {
021. if (this.closed) {
022. throw new IllegalStateException("Closed MessageStore.");
023. }
024. //如果启动异步写入并且消息长度小于一次提交的最大值maxTransferSize，则将该消息放入异步写入队列
025. if (this.useGroupCommit() && buffer.remaining() &lt; this.maxTransferSize) {
026. this.bufferQueue.offer(new WriteRequest(buffer, cb));
027. } else {
028. Location location = null;
029. final int remainning = buffer.remaining();
030. this.writeLock.lock();
031. try {
032. final Segment cur = this.segments.last();
033. final long offset = cur.start + cur.fileMessageSet.append(buffer);
034. this.mayBeFlush(1);
035. this.mayBeRoll();
036. location = Location.create(offset, remainning);
037. } catch (final IOException e) {
038. log.error("Append file failed", e);
039. location = Location.InvalidLocaltion;
040. } finally {
041. this.writeLock.unlock();
042. if (cb != null) {
043. cb.appendComplete(location);
044. }
045. //调用回调方法，数据写入文件缓存
046. }
047. }
048. }
049. ……
050. //判断是否启用异步写入，如果设置为unflushThreshold &lt;=0的数字，则认为启动异步写入；如果设置为unflushThreshold =1，则是同步写入，即每写入一个消息都会提交到磁盘；如果unflushThreshold&gt;0，则是依赖组提交或者是超时提交
051. private boolean useGroupCommit() {
052. return this.unflushThreshold &lt;= 0;
053. }
054. @Override
055. public void run() {
056. // 等待force的队列
057. final LinkedList&lt;WriteRequest&gt; toFlush = new LinkedList&lt;WriteRequest&gt;();
058. WriteRequest req = null;
059. long lastFlushPos = 0;
060. Segment last = null;
061. //存储没有关闭并且线程没有被中断
062. while (!this.closed && !Thread.currentThread().isInterrupted()) {
063. try {
064. if (last == null) {
065. //获取最后的一个segment，将消息写入最后segment对应的文件
066. last = this.segments.last();
067. lastFlushPos = last.fileMessageSet.highWaterMark();
068. }
069. if (req == null) {
070. //如果等待提交到磁盘的队列toFlush为空，则两种可能：一、刚刚提交完，列表为空；二、等待写入消息的队列为空，如果判断toFlush，则调用bufferQueue.take()方法，可以阻塞住队列，而如果toFlush不为空，则调用bufferQueue.poll，这是提高性能的一种做法。
071. if (toFlush.isEmpty()) {
072. req = this.bufferQueue.take();
073. } else {
074. req = this.bufferQueue.poll();
075. //如果当前请求为空，表明等待写入的消息已经没有了，这时候文件缓存中的消息需要提交到磁盘，防止消息丢失；或者如果已经写入文件的大小大于maxTransferSize，则提交到磁盘
076. //这里需要注意的是，会出现这样一种情况，刚好最后一个segment的文件快满了，这时候是不会roll出一个新的segment写入消息的，而是直接追加到原来的segment尾部，可能导致segment对应的文件大小大于配置的单个segment大小
077. if (req == null || last.fileMessageSet.getSizeInBytes() &gt; lastFlushPos + this.maxTransferSize) {
078. // 强制force，确保内容保存到磁盘
079. last.fileMessageSet.flush();
080. lastFlushPos = last.fileMessageSet.highWaterMark();
081. // 通知回调
082. //异步写入比组写入可靠，因为异步写入一定是提交到磁盘的时候才进行回调的，而组写入如果依赖组提交的方式，则可能会丢失数据，因为组写入在消息写入到文件缓存的时候就进行回调了(除非设置unflushThreshold=1)
083. for (final WriteRequest request : toFlush) {
084. request.cb.appendComplete(request.result);
085. }
086. toFlush.clear();
087. // 是否需要roll
088. this.mayBeRoll();
089. // 如果切换文件，重新获取last
090. if (this.segments.last() != last) {
091. last = null;
092. }
093. continue;
094. }
095. }
096. }
097. if (req == null) {
098. continue;
099. }
100. //写入文件，并计算写入位置
101. final int remainning = req.buf.remaining();
102. //写入位置为：当前segment给定的值 + 加上文件已有的长度
103. final long offset = last.start + last.fileMessageSet.append(req.buf);
104. req.result = Location.create(offset, remainning);
105. if (req.cb != null) {
106. toFlush.add(req);
107. }
108. req = null;
109. } catch (final IOException e) {
110. log.error("Append message failed,\*critical error\*,the group commit thread would be terminated.", e);
111. // TODO io异常没办法处理了，简单跳出?
112. break;
113. } catch (final InterruptedException e) {
114. // ignore
115. }
116. }
117. // terminated
118. //关闭store 前，将等待写入队列中的剩余消息写入最后一个文件，这时候如果最后一个Segment满了也不会roll出新的Segment，持续的将消息写入到最后一个Segment，所以这时候也会发生Segment的size大于配置的size的情况
119. try {
120. for (WriteRequest request : this.bufferQueue) {
121. final int remainning = request.buf.remaining();
122. final long offset = last.start + last.fileMessageSet.append(request.buf);
123. if (request.cb != null) {
124. request.cb.appendComplete(Location.create(offset, remainning));
125. }
126. }
127. this.bufferQueue.clear();
128. } catch (IOException e) {
129. log.error("Append message failed", e);
130. }
131. }
132. ……
133. //Append多个消息，返回写入的位置
134. public void append(final List&lt;Long&gt; msgIds, final List&lt;PutCommand&gt; putCmds, final AppendCallback cb) {
135. this.appendBuffer(MessageUtils.makeMessageBuffer(msgIds, putCmds), cb);
136. }
137. /\**
138. * 重放事务操作，如果消息没有存储成功，则重新存储，并返回新的位置
139. \*/
140. public void replayAppend(final long offset, final int length, final int checksum, final List&lt;Long&gt; msgIds,
141. final List&lt;PutCommand&gt; reqs, final AppendCallback cb) throws IOException {
142. //如果消息没有存储，则重新存储，写到最后一个Segment尾部
143. final Segment segment = this.findSegment(this.segments.view(), offset);
144. if (segment == null) {
145. this.append(msgIds, reqs, cb);
146. } else {
147. final MessageSet messageSet = segment.fileMessageSet.slice(offset - segment.start, offset - segment.start + length);
148. final ByteBuffer buf = ByteBuffer.allocate(length);
149. messageSet.read(buf, offset - segment.start);
150. buf.flip();
151. final byte\[] bytes = new byte\[buf.remaining()];
152. buf.get(bytes);
153. // 这个校验和是整个消息的校验和，这跟message的校验和不一样，注意区分
154. final int checkSumInDisk = CheckSum.crc32(bytes);
155. // 没有存入，则重新存储
156. if (checksum != checkSumInDisk) {
157. this.append(msgIds, reqs, cb);
158. } else {
159. // 正常存储了消息，无需处理
160. if (cb != null) {
161. this.notifyCallback(cb, null);
162. }
163. }
164. }
165. }
166. //判断是否需要roll，如果当前 messagestore最后一个segment的size&gt;=配置的segment size，则产生新的segment，并将新的segment作为最后一个segment，原来最后的segment提交一次，并将mutable设置为false
167. private void mayBeRoll() throws IOException {
168. if (this.segments.last().fileMessageSet.getSizeInBytes() &gt;= this.metaConfig.getMaxSegmentSize()) {
169. this.roll();
170. }
171. }
172. String nameFromOffset(final long offset) {
173. final NumberFormat nf = NumberFormat.getInstance();
174. nf.setMinimumIntegerDigits(20);
175. nf.setMaximumFractionDigits(0);
176. nf.setGroupingUsed(false);
177. return nf.format(offset) + FILE\_SUFFIX;
178. }
179. private long nextAppendOffset() throws IOException {
180. final Segment last = this.segments.last();
181. last.fileMessageSet.flush();
182. return last.start + last.size();
183. }
184. private void roll() throws IOException {
185. final long newOffset = this.nextAppendOffset();
186. //新的segment对应的存储文件的命名为原来最后一个segment的起始位置 + segment的size
187. final File newFile = new File(this.partitionDir, this.nameFromOffset(newOffset));
188. this.segments.last().fileMessageSet.flush();
189. this.segments.last().fileMessageSet.setMutable(false);
190. this.segments.append(new Segment(newOffset, newFile));
191. }
192. //判断是否需要消息提交到磁盘，判断的条件有两个，如果达到组提交的条件或者达到间隔的提交时间
193. private void mayBeFlush(final int numOfMessages) throws IOException {
194. if (this.unflushed.addAndGet(numOfMessages) &gt; this.metaConfig.getTopicConfig(this.topic).getUnflushThreshold()
195. || SystemTimer.currentTimeMillis() - this.lastFlushTime.get() &gt; this.metaConfig.getTopicConfig(this.topic).getUnflushInterval()) {
196. this.flush0();
197. }
198. }
199. //提交到磁盘
200. public void flush() throws IOException {
201. this.writeLock.lock();
202. try {
203. this.flush0();
204. } finally {
205. this.writeLock.unlock();
206. }
207. }
208. private void flush0() throws IOException {
209. if (this.useGroupCommit()) {
210. return;
211. }
212. //由于只有最后一个segment是可变，即可写入消息的，所以只需要提交最后一个segment的消息
213. this.segments.last().fileMessageSet.flush();
214. this.unflushed.set(0);
215. this.lastFlushTime.set(SystemTimer.currentTimeMillis());
216. }
217. @Override
218. public void close() throws IOException {
219. this.closed = true;
220. this.interrupt();
221. //等待子线程完成写完异步队列中剩余未写的消息
222. try {
223. this.join(500);
224. } catch (InterruptedException e) {
225. Thread.currentThread().interrupt();
226. }
227. //关闭segment，保证内容都已经提交到磁盘
228. for (final Segment segment : this.segments.view()) {
229. segment.fileMessageSet.close();
230. }
231. }
232. //返回segment的信息，主要包括segment的开始位置以及 segment 的size
233. public List&lt;SegmentInfo&gt; getSegmentInfos() {
234. final List&lt;SegmentInfo&gt; rt = new ArrayList&lt;SegmentInfo&gt;();
235. for (final Segment seg : this.segments.view()) {
236. rt.add(new SegmentInfo(seg.start, seg.size()));
237. }
238. return rt;
239. }
240. /\**
241. * 返回当前最大可读的offset
242. \*/
243. //需要注意的是，在文件缓存中的消息是不可读的，可以通过getSizeInBytes（）方法来判断还有多少内容还在文件缓存中，getSizeInBytes()方法返回的值是包括所有在磁盘和缓存中的size
244. public long getMaxOffset() {
245. final Segment last = this.segments.last();
246. if (last != null) {
247. return last.start + last.size();
248. } else {
249. return 0;
250. }
251. }
252. /\**
253. * 返回当前最小可读的offset
254. \*/
255. public long getMinOffset() {
256. Segment first = this.segments.first();
257. if (first != null) {
258. return first.start;
259. } else {
260. return 0;
261. }
262. }
263. /\**
264. * 根据offset和maxSize返回所在MessageSet, 当offset超过最大offset的时候返回null，
265. * 当offset小于最小offset的时候抛出ArrayIndexOutOfBounds异常
266. \*/
267. //代码的注释以及清楚的解析了作用
268. public MessageSet slice(final long offset, final int maxSize) throws IOException {
269. final Segment segment = this.findSegment(this.segments.view(), offset);
270. if (segment == null) {
271. return null;
272. } else {
273. return segment.fileMessageSet.slice(offset - segment.start, offset - segment.start + maxSize);
274. }
275. }
276. /\**
277. * 根据offset查找文件,如果超过尾部，则返回null，如果在头部之前，则抛出ArrayIndexOutOfBoundsException
278. \*/
279. //指定位置找到对应的segment，由于前面的文件组织方式，所以这里可以采用2分查找的方式，
280. //效率很高
281. Segment findSegment(final Segment\[] segments, final long offset) {
282. if (segments == null || segments.length &lt; 1) {
283. return null;
284. }
285. // 老的数据不存在，返回最近最老的数据
286. final Segment last = segments\[segments.length - 1];
287. // 在头部以前，抛出异常
288. if (offset &lt; segments\[0].start) {
289. throw new ArrayIndexOutOfBoundsException();
290. }
291. // 刚好在尾部或者超出范围，返回null
292. if (offset &gt;= last.start + last.size()) {
293. return null;
294. }
295. // 根据offset二分查找
296. int low = 0;
297. int high = segments.length - 1;
298. while (low &lt;= high) {
299. final int mid = high + low &gt;&gt;&gt; 1;
300. final Segment found = segments\[mid];
301. if (found.contains(offset)) {
302. return found;
303. } else if (offset &lt; found.start) {
304. high = mid - 1;
305. } else {
306. low = mid + 1;
307. }
308. }
309. return null;
310. }