ITeye博客

MetaQ技术内幕——源码分析(三)

wbj0110 · 2014-05-31 12:45 · MetaQ · 编程语言 · metaq · Markdown

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

 

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

 

 

Java代码 复制代码 收藏代码

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

[java] view plaincopy在CODE上查看代码片派生到我的代码片

 

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

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

 

Java代码 复制代码 收藏代码

  1. public MessageStore(final String topic, final int partition, final MetaConfig metaConfig,
  2. final DeletePolicy deletePolicy, final long offsetIfCreate) throws IOException {
  3. this.metaConfig = metaConfig; //全局配置信息
  4. this.topic = topic; //当前主题
  5. final TopicConfig topicConfig = this.metaConfig.getTopicConfig(this.topic);
  6. String dataPath = metaConfig.getDataPath(); //当前分区的存储路径
  7. if (topicConfig != null) {
  8. dataPath = topicConfig.getDataPath();
  9. }
  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 > 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 plaincopy在CODE上查看代码片派生到我的代码片

 

  1. public MessageStore(final String topic, final int partition, final MetaConfig metaConfig,
  2. final DeletePolicy deletePolicy, final long offsetIfCreate) throws IOException {
  3. this.metaConfig = metaConfig; //全局配置信息
  4. this.topic = topic; //当前主题
  5. final TopicConfig topicConfig = this.metaConfig.getTopicConfig(this.topic);
  6. String dataPath = metaConfig.getDataPath(); //当前分区的存储路径
  7. if (topicConfig != null) {
  8. dataPath = topicConfig.getDataPath();
  9. }
  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 > 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<= 0,则认为启动异步写入的方式)

 

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

 

Java代码 复制代码 收藏代码

  1. private void loadSegments(final long offsetIfCreate) throws IOException {
  2. final List<Segment> accum = new ArrayList<Segment>();
  3. final File[] ls = this.partitionDir.listFiles();
  4. if (ls != null) {
  5. //遍历目录下的所有.meta后缀的数据文件,将所有文件都变为不可变的文件
  6. for (final File file : ls) {
  7. if (file.isFile() && file.toString().endsWith(FILE_SUFFIX)) {
  8. if (!file.canRead()) {
  9. 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<Segment>() {
  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 > 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 plaincopy在CODE上查看代码片派生到我的代码片

 

  1. private void loadSegments(final long offsetIfCreate) throws IOException {
  2. final List<Segment> accum = new ArrayList<Segment>();
  3. final File[] ls = this.partitionDir.listFiles();
  4. if (ls != null) {
  5. //遍历目录下的所有.meta后缀的数据文件,将所有文件都变为不可变的文件
  6. for (final File file : ls) {
  7. if (file.isFile() && file.toString().endsWith(FILE_SUFFIX)) {
  8. if (!file.canRead()) {
  9. 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<Segment>() {
  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 > 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):

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

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

 

Java代码 复制代码 收藏代码

  1. private void validateSegments(final List<Segment> segments) {
  2. //验证按升序排序的Segment是否前后衔接,确保文件没有被篡改和破坏(这里的验证是比较简单的验证,消息内容的验证在FileMessageSet中,通过比较checksum进行验证,在前面的篇幅中介绍过,这两种方式结合可以在范围上从大到小进行验证,保证内容基本不被破坏和篡改)
  3. this.writeLock.lock();
  4. try {
  5. for (int i = 0; i < segments.size() - 1; i++) {
  6. final Segment curr = segments.get(i);
  7. final Segment next = segments.get(i + 1);
  8. if (curr.start + curr.size() != next.start) {
  9. 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 plaincopy在CODE上查看代码片派生到我的代码片

 

  1. private void validateSegments(final List<Segment> segments) {
  2. //验证按升序排序的Segment是否前后衔接,确保文件没有被篡改和破坏(这里的验证是比较简单的验证,消息内容的验证在FileMessageSet中,通过比较checksum进行验证,在前面的篇幅中介绍过,这两种方式结合可以在范围上从大到小进行验证,保证内容基本不被破坏和篡改)
  3. this.writeLock.lock();
  4. try {
  5. for (int i = 0; i < segments.size() - 1; i++) {
  6. final Segment curr = segments.get(i);
  7. final Segment next = segments.get(i + 1);
  8. if (curr.start + curr.size() != next.start) {
  9. 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代码 复制代码 收藏代码

  1. //添加消息的方式有两种,同步和异步
  2. public void append(final long msgId, final PutCommand req, final AppendCallback cb) {
  3. //首先将内容包装成前面介绍过的消息存储格式
  4. this.appendBuffer(MessageUtils.makeMessageBuffer(msgId, req), cb);
  5. }
  6. //异步写入的包装类
  7. private static class WriteRequest {
  8. public final ByteBuffer buf;
  9. public final AppendCallback cb;
  10. public Location result;
  11. public WriteRequest(final ByteBuffer buf, final AppendCallback cb) {
  12. super();
  13. this.buf = buf;
  14. this.cb = cb;
  15. }
  16. }
  17. //这里比较好的设计是采用回调的方式来,对于异步写入实现就变得非常容易
  18. //AppendCallback返回的是消息成功写入的位置Location(起始位置和消息长度),该Location并不是相对于当前Segment的开始位置0,而是相对于当前Segment给定的值(对应文件命名值即为给定的值),以后查询消息的时候直接使用该位置就可以快速定位到消息写入到哪个文件
  19. //这也就是为什么文件名的命名采用前后衔接的方式,这也通过2分查找可以快速定位消息的位置
  20. private void appendBuffer(final ByteBuffer buffer, final AppendCallback cb) {
  21. if (this.closed) {
  22. throw new IllegalStateException("Closed MessageStore.");
  23. }
  24. //如果启动异步写入并且消息长度小于一次提交的最大值maxTransferSize,则将该消息放入异步写入队列
  25. if (this.useGroupCommit() && buffer.remaining() < this.maxTransferSize) {
  26. this.bufferQueue.offer(new WriteRequest(buffer, cb));
  27. } else {
  28. Location location = null;
  29. final int remainning = buffer.remaining();
  30. this.writeLock.lock();
  31. try {
  32. final Segment cur = this.segments.last();
  33. final long offset = cur.start + cur.fileMessageSet.append(buffer);
  34. this.mayBeFlush(1);
  35. this.mayBeRoll();
  36. location = Location.create(offset, remainning);
  37. } catch (final IOException e) {
  38. log.error("Append file failed", e);
  39. location = Location.InvalidLocaltion;
  40. } finally {
  41. this.writeLock.unlock();
  42. if (cb != null) {
  43. cb.appendComplete(location);
  44. }
  45. //调用回调方法,数据写入文件缓存
  46. }
  47. }
  48. }
  49. ……
  50. //判断是否启用异步写入,如果设置为unflushThreshold <=0的数字,则认为启动异步写入;如果设置为unflushThreshold =1,则是同步写入,即每写入一个消息都会提交到磁盘;如果unflushThreshold>0,则是依赖组提交或者是超时提交
  51. private boolean useGroupCommit() {
  52. return this.unflushThreshold <= 0;
  53. }
  54. @Override
  55. public void run() {
  56. // 等待force的队列
  57. final LinkedList<WriteRequest> toFlush = new LinkedList<WriteRequest>();
  58. WriteRequest req = null;
  59. long lastFlushPos = 0;
  60. Segment last = null;
  61. //存储没有关闭并且线程没有被中断
  62. while (!this.closed && !Thread.currentThread().isInterrupted()) {
  63. try {
  64. if (last == null) {
  65. //获取最后的一个segment,将消息写入最后segment对应的文件
  66. last = this.segments.last();
  67. lastFlushPos = last.fileMessageSet.highWaterMark();
  68. }
  69. if (req == null) {
  70. //如果等待提交到磁盘的队列toFlush为空,则两种可能:一、刚刚提交完,列表为空;二、等待写入消息的队列为空,如果判断toFlush,则调用bufferQueue.take()方法,可以阻塞住队列,而如果toFlush不为空,则调用bufferQueue.poll,这是提高性能的一种做法。
  71. if (toFlush.isEmpty()) {
  72. req = this.bufferQueue.take();
  73. } else {
  74. req = this.bufferQueue.poll();
  75. //如果当前请求为空,表明等待写入的消息已经没有了,这时候文件缓存中的消息需要提交到磁盘,防止消息丢失;或者如果已经写入文件的大小大于maxTransferSize,则提交到磁盘
  76. //这里需要注意的是,会出现这样一种情况,刚好最后一个segment的文件快满了,这时候是不会roll出一个新的segment写入消息的,而是直接追加到原来的segment尾部,可能导致segment对应的文件大小大于配置的单个segment大小
  77. if (req == null || last.fileMessageSet.getSizeInBytes() > lastFlushPos + this.maxTransferSize) {
  78. // 强制force,确保内容保存到磁盘
  79. last.fileMessageSet.flush();
  80. lastFlushPos = last.fileMessageSet.highWaterMark();
  81. // 通知回调
  82. //异步写入比组写入可靠,因为异步写入一定是提交到磁盘的时候才进行回调的,而组写入如果依赖组提交的方式,则可能会丢失数据,因为组写入在消息写入到文件缓存的时候就进行回调了(除非设置unflushThreshold=1)
  83. for (final WriteRequest request : toFlush) {
  84. request.cb.appendComplete(request.result);
  85. }
  86. toFlush.clear();
  87. // 是否需要roll
  88. this.mayBeRoll();
  89. // 如果切换文件,重新获取last
  90. if (this.segments.last() != last) {
  91. last = null;
  92. }
  93. continue;
  94. }
  95. }
  96. }
  97. if (req == null) {
  98. continue;
  99. }
  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<Long> msgIds, final List<PutCommand> 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<Long> msgIds,
  141. final List<PutCommand> 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>=配置的segment size,则产生新的segment,并将新的segment作为最后一个segment,原来最后的segment提交一次,并将mutable设置为false
  167. private void mayBeRoll() throws IOException {
  168. if (this.segments.last().fileMessageSet.getSizeInBytes() >=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) >this.metaConfig.getTopicConfig(this.topic).getUnflushThreshold()
  195. || SystemTimer.currentTimeMillis() - this.lastFlushTime.get() >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<SegmentInfo> getSegmentInfos() {
  234. final List<SegmentInfo> rt = new ArrayList<SegmentInfo>();
  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 < 1) {
  283. return null;
  284. }
  285. // 老的数据不存在,返回最近最老的数据
  286. final Segment last = segments[segments.length - 1];
  287. // 在头部以前,抛出异常
  288. if (offset < segments[0].start) {
  289. throw new ArrayIndexOutOfBoundsException();
  290. }
  291. // 刚好在尾部或者超出范围,返回null
  292. if (offset >= last.start + last.size()) {
  293. return null;
  294. }
  295. // 根据offset二分查找
  296. int low = 0;
  297. int high = segments.length - 1;
  298. while (low <= high) {
  299. final int mid = high + low >>> 1;
  300. final Segment found = segments[mid];
  301. if (found.contains(offset)) {
  302. return found;
  303. } else if (offset < found.start) {
  304. high = mid - 1;
  305. } else {
  306. low = mid + 1;
  307. }
  308. }
  309. return null;
  310. }

[java] view plaincopy在CODE上查看代码片派生到我的代码片

 

  1. //添加消息的方式有两种,同步和异步
  2. public void append(final long msgId, final PutCommand req, final AppendCallback cb) {
  3. //首先将内容包装成前面介绍过的消息存储格式
  4. this.appendBuffer(MessageUtils.makeMessageBuffer(msgId, req), cb);
  5. }
  6. //异步写入的包装类
  7. private static class WriteRequest {
  8. public final ByteBuffer buf;
  9. public final AppendCallback cb;
  10. public Location result;
  11. public WriteRequest(final ByteBuffer buf, final AppendCallback cb) {
  12. super();
  13. this.buf = buf;
  14. this.cb = cb;
  15. }
  16. }
  17. //这里比较好的设计是采用回调的方式来,对于异步写入实现就变得非常容易
  18. //AppendCallback返回的是消息成功写入的位置Location(起始位置和消息长度),该Location并不是相对于当前Segment的开始位置0,而是相对于当前Segment给定的值(对应文件命名值即为给定的值),以后查询消息的时候直接使用该位置就可以快速定位到消息写入到哪个文件
  19. //这也就是为什么文件名的命名采用前后衔接的方式,这也通过2分查找可以快速定位消息的位置
  20. private void appendBuffer(final ByteBuffer buffer, final AppendCallback cb) {
  21. if (this.closed) {
  22. throw new IllegalStateException("Closed MessageStore.");
  23. }
  24. //如果启动异步写入并且消息长度小于一次提交的最大值maxTransferSize,则将该消息放入异步写入队列
  25. if (this.useGroupCommit() && buffer.remaining() < this.maxTransferSize) {
  26. this.bufferQueue.offer(new WriteRequest(buffer, cb));
  27. } else {
  28. Location location = null;
  29. final int remainning = buffer.remaining();
  30. this.writeLock.lock();
  31. try {
  32. final Segment cur = this.segments.last();
  33. final long offset = cur.start + cur.fileMessageSet.append(buffer);
  34. this.mayBeFlush(1);
  35. this.mayBeRoll();
  36. location = Location.create(offset, remainning);
  37. } catch (final IOException e) {
  38. log.error("Append file failed", e);
  39. location = Location.InvalidLocaltion;
  40. } finally {
  41. this.writeLock.unlock();
  42. if (cb != null) {
  43. cb.appendComplete(location);
  44. }
  45. //调用回调方法,数据写入文件缓存
  46. }
  47. }
  48. }
  49. ……
  50. //判断是否启用异步写入,如果设置为unflushThreshold <=0的数字,则认为启动异步写入;如果设置为unflushThreshold =1,则是同步写入,即每写入一个消息都会提交到磁盘;如果unflushThreshold>0,则是依赖组提交或者是超时提交
  51. private boolean useGroupCommit() {
  52. return this.unflushThreshold <= 0;
  53. }
  54. @Override
  55. public void run() {
  56. // 等待force的队列
  57. final LinkedList<WriteRequest> toFlush = new LinkedList<WriteRequest>();
  58. WriteRequest req = null;
  59. long lastFlushPos = 0;
  60. Segment last = null;
  61. //存储没有关闭并且线程没有被中断
  62. while (!this.closed && !Thread.currentThread().isInterrupted()) {
  63. try {
  64. if (last == null) {
  65. //获取最后的一个segment,将消息写入最后segment对应的文件
  66. last = this.segments.last();
  67. lastFlushPos = last.fileMessageSet.highWaterMark();
  68. }
  69. if (req == null) {
  70. //如果等待提交到磁盘的队列toFlush为空,则两种可能:一、刚刚提交完,列表为空;二、等待写入消息的队列为空,如果判断toFlush,则调用bufferQueue.take()方法,可以阻塞住队列,而如果toFlush不为空,则调用bufferQueue.poll,这是提高性能的一种做法。
  71. if (toFlush.isEmpty()) {
  72. req = this.bufferQueue.take();
  73. } else {
  74. req = this.bufferQueue.poll();
  75. //如果当前请求为空,表明等待写入的消息已经没有了,这时候文件缓存中的消息需要提交到磁盘,防止消息丢失;或者如果已经写入文件的大小大于maxTransferSize,则提交到磁盘
  76. //这里需要注意的是,会出现这样一种情况,刚好最后一个segment的文件快满了,这时候是不会roll出一个新的segment写入消息的,而是直接追加到原来的segment尾部,可能导致segment对应的文件大小大于配置的单个segment大小
  77. if (req == null || last.fileMessageSet.getSizeInBytes() > lastFlushPos + this.maxTransferSize) {
  78. // 强制force,确保内容保存到磁盘
  79. last.fileMessageSet.flush();
  80. lastFlushPos = last.fileMessageSet.highWaterMark();
  81. // 通知回调
  82. //异步写入比组写入可靠,因为异步写入一定是提交到磁盘的时候才进行回调的,而组写入如果依赖组提交的方式,则可能会丢失数据,因为组写入在消息写入到文件缓存的时候就进行回调了(除非设置unflushThreshold=1)
  83. for (final WriteRequest request : toFlush) {
  84. request.cb.appendComplete(request.result);
  85. }
  86. toFlush.clear();
  87. // 是否需要roll
  88. this.mayBeRoll();
  89. // 如果切换文件,重新获取last
  90. if (this.segments.last() != last) {
  91. last = null;
  92. }
  93. continue;
  94. }
  95. }
  96. }
  97. if (req == null) {
  98. continue;
  99. }
  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<Long> msgIds, final List<PutCommand> 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<Long> msgIds,
  141. final List<PutCommand> 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>=配置的segment size,则产生新的segment,并将新的segment作为最后一个segment,原来最后的segment提交一次,并将mutable设置为false
  167. private void mayBeRoll() throws IOException {
  168. if (this.segments.last().fileMessageSet.getSizeInBytes() >= 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) > this.metaConfig.getTopicConfig(this.topic).getUnflushThreshold()
  195. || SystemTimer.currentTimeMillis() - this.lastFlushTime.get() > 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<SegmentInfo> getSegmentInfos() {
  234. final List<SegmentInfo> rt = new ArrayList<SegmentInfo>();
  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 < 1) {
  283. return null;
  284. }
  285. // 老的数据不存在,返回最近最老的数据
  286. final Segment last = segments[segments.length - 1];
  287. // 在头部以前,抛出异常
  288. if (offset < segments[0].start) {
  289. throw new ArrayIndexOutOfBoundsException();
  290. }
  291. // 刚好在尾部或者超出范围,返回null
  292. if (offset >= last.start + last.size()) {
  293. return null;
  294. }
  295. // 根据offset二分查找
  296. int low = 0;
  297. int high = segments.length - 1;
  298. while (low <= high) {
  299. final int mid = high + low >>> 1;
  300. final Segment found = segments[mid];
  301. if (found.contains(offset)) {
  302. return found;
  303. } else if (offset < found.start) {
  304. high = mid - 1;
  305. } else {
  306. low = mid + 1;
  307. }
  308. }
  309. return null;
  310. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。