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

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



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

Java代码 复制代码 收藏代码
  1. public class MessageStore extends Thread implements Closeable { 
  2.      ……. 
public class MessageStore extends Thread implements Closeable {
     …….
}

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

	// Make a copy to avoid getting it again and again.
	this.maxTransferSize = metaConfig.getMaxTransferSize();
	//启动异步写入的时候,消息提交到磁盘的size配置,同时也是配置组写入时,消息最大长度的控制参数,如果消息长度大于该参数,则会同步写入
	this.maxTransferSize = this.maxTransferSize > ONE_M_BYTES ? ONE_M_BYTES : this.maxTransferSize;

	// Check directory and load exists segments.
	this.checkDir(this.partitionDir);
	this.loadSegments(offsetIfCreate);
	if (this.useGroupCommit()) {
		this.start();
	}
}

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

		if (ls != null) {
            //遍历目录下的所有.meta后缀的数据文件,将所有文件都变为不可变的文件
			for (final File file : ls) {
				if (file.isFile() && file.toString().endsWith(FILE_SUFFIX)) {
					if (!file.canRead()) {
						throw new IOException("Could not read file " + file);
					}
					final String filename = file.getName();
					final long start = Long.parseLong(filename.substring(0, filename.length() - FILE_SUFFIX.length()));
					// 先作为不可变的加载进来
					accum.add(new Segment(start, file, false));
				}
			}
		}
		
		if (accum.size() == 0) {
			// 没有可用的文件,创建一个,索引从offsetIfCreate开始
			final File newFile = new File(this.partitionDir, this.nameFromOffset(offsetIfCreate));
			accum.add(new Segment(offsetIfCreate, newFile));
		} else {
			// 至少有一个文件,校验并按照start升序排序
			Collections.sort(accum, new Comparator<Segment>() {
				@Override
				public int compare(final Segment o1, final Segment o2) {
					if (o1.start == o2.start) {
						return 0;
					} else if (o1.start > o2.start) {
						return 1;
					} else {
						return -1;
					}
				}
			});
			// 校验文件,是否前后衔接,如果不是,则认为数据文件被破坏或者篡改,抛出异常
			this.validateSegments(accum);
			// 最后一个文件修改为可变
			final Segment last = accum.remove(accum.size() - 1);
			last.fileMessageSet.close();
			log.info("Loading the last segment in mutable mode and running recover on " + last.file.getAbsolutePath());
			final Segment mutable = new Segment(last.start, last.file);
			accum.add(mutable);
			log.info("Loaded " + accum.size() + " segments...");
		}

		this.segments = new SegmentList(accum.toArray(new Segment[accum.size()]));
       //多个segmentg通过SegmentList组织起来,SegmentList能保证在并发访问下的删除、添加保持一致性,SegmentList没有采用java的关键字 synchronized进行同步,而是使用类似cvs原语的方式进行同步访问(因为绝大部分情况下并没有并发问题,可以极大的提高效率),该类比较简单就不再分析
}

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

   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.  
  12.         public WriteRequest(final ByteBuffer buf, final AppendCallback cb) { 
  13.             super(); 
  14.             this.buf = buf; 
  15.             this.cb = cb; 
  16.         } 
  17.     } 
  18.  
  19.   //这里比较好的设计是采用回调的方式来,对于异步写入实现就变得非常容易 
  20. //AppendCallback返回的是消息成功写入的位置Location(起始位置和消息长度),该Location并不是相对于当前Segment的开始位置0,而是相对于当前Segment给定的值(对应文件命名值即为给定的值),以后查询消息的时候直接使用该位置就可以快速定位到消息写入到哪个文件 
  21. //这也就是为什么文件名的命名采用前后衔接的方式,这也通过2分查找可以快速定位消息的位置 
  22.     private void appendBuffer(final ByteBuffer buffer, final AppendCallback cb) { 
  23.         if (this.closed) { 
  24.             throw new IllegalStateException("Closed MessageStore."); 
  25.         } 
  26.         //如果启动异步写入并且消息长度小于一次提交的最大值maxTransferSize,则将该消息放入异步写入队列 
  27.         if (this.useGroupCommit() && buffer.remaining() < this.maxTransferSize) { 
  28.             this.bufferQueue.offer(new WriteRequest(buffer, cb)); 
  29.         } else
  30.             Location location = null
  31.             final int remainning = buffer.remaining(); 
  32.             this.writeLock.lock(); 
  33.             try
  34.                 final Segment cur = this.segments.last(); 
  35.                 final long offset = cur.start + cur.fileMessageSet.append(buffer); 
  36.                 this.mayBeFlush(1); 
  37.                 this.mayBeRoll(); 
  38.                 location = Location.create(offset, remainning); 
  39.             } catch (final IOException e) { 
  40.                 log.error("Append file failed", e); 
  41.                 location = Location.InvalidLocaltion; 
  42.             } finally
  43.                 this.writeLock.unlock(); 
  44.                 if (cb != null) { 
  45.                     cb.appendComplete(location); 
  46.                 } 
  47.                 //调用回调方法,数据写入文件缓存 
  48.             } 
  49.         } 
  50.     } 
  51.  
  52. …… 
  53.  
  54.   //判断是否启用异步写入,如果设置为unflushThreshold <=0的数字,则认为启动异步写入;如果设置为unflushThreshold =1,则是同步写入,即每写入一个消息都会提交到磁盘;如果unflushThreshold>0,则是依赖组提交或者是超时提交 
  55.     private boolean useGroupCommit() { 
  56.         return this.unflushThreshold <= 0
  57.     } 
  58.  
  59.     @Override 
  60.     public void run() { 
  61.         // 等待force的队列 
  62.         final LinkedList<WriteRequest> toFlush = new LinkedList<WriteRequest>(); 
  63.         WriteRequest req = null
  64.         long lastFlushPos = 0
  65.         Segment last = null
  66.         //存储没有关闭并且线程没有被中断 
  67.         while (!this.closed && !Thread.currentThread().isInterrupted()) { 
  68.             try
  69.                 if (last == null) { 
  70.                     //获取最后的一个segment,将消息写入最后segment对应的文件 
  71.                     last = this.segments.last(); 
  72.                     lastFlushPos = last.fileMessageSet.highWaterMark(); 
  73.                 } 
  74.                 if (req == null) { 
  75.                      //如果等待提交到磁盘的队列toFlush为空,则两种可能:一、刚刚提交完,列表为空;二、等待写入消息的队列为空,如果判断toFlush,则调用bufferQueue.take()方法,可以阻塞住队列,而如果toFlush不为空,则调用bufferQueue.poll,这是提高性能的一种做法。 
  76.                     if (toFlush.isEmpty()) { 
  77.                         req = this.bufferQueue.take(); 
  78.                     } else
  79.                         req = this.bufferQueue.poll(); 
  80.                         //如果当前请求为空,表明等待写入的消息已经没有了,这时候文件缓存中的消息需要提交到磁盘,防止消息丢失;或者如果已经写入文件的大小大于maxTransferSize,则提交到磁盘 
  81.                           //这里需要注意的是,会出现这样一种情况,刚好最后一个segment的文件快满了,这时候是不会roll出一个新的segment写入消息的,而是直接追加到原来的segment尾部,可能导致segment对应的文件大小大于配置的单个segment大小 
  82.                         if (req == null || last.fileMessageSet.getSizeInBytes() > lastFlushPos + this.maxTransferSize) { 
  83.                             // 强制force,确保内容保存到磁盘 
  84.                             last.fileMessageSet.flush(); 
  85.                             lastFlushPos = last.fileMessageSet.highWaterMark(); 
  86.                             // 通知回调 
  87.                             //异步写入比组写入可靠,因为异步写入一定是提交到磁盘的时候才进行回调的,而组写入如果依赖组提交的方式,则可能会丢失数据,因为组写入在消息写入到文件缓存的时候就进行回调了(除非设置unflushThreshold=1) 
  88.                             for (final WriteRequest request : toFlush) { 
  89.                                 request.cb.appendComplete(request.result); 
  90.                             } 
  91.                             toFlush.clear(); 
  92.                             // 是否需要roll 
  93.                             this.mayBeRoll(); 
  94.                             // 如果切换文件,重新获取last 
  95.                             if (this.segments.last() != last) { 
  96.                                 last = null
  97.                             } 
  98.                             continue
  99.                         } 
  100.                     } 
  101.                 } 
  102.  
  103.                 if (req == null) { 
  104.                     continue
  105.                 } 
  106.                 //写入文件,并计算写入位置 
  107.                 final int remainning = req.buf.remaining(); 
  108.                 //写入位置为:当前segment给定的值 + 加上文件已有的长度  
  109. final long offset = last.start + last.fileMessageSet.append(req.buf); 
  110.                 req.result = Location.create(offset, remainning); 
  111.                 if (req.cb != null) { 
  112.                     toFlush.add(req); 
  113.                 } 
  114.                 req = null
  115.             } catch (final IOException e) { 
  116.                 log.error("Append message failed,*critical error*,the group commit thread would be terminated.", e); 
  117.                 // TODO io异常没办法处理了,简单跳出? 
  118.                 break
  119.             } catch (final InterruptedException e) { 
  120.                 // ignore 
  121.             } 
  122.         } 
  123.         // terminated 
  124.         //关闭store 前,将等待写入队列中的剩余消息写入最后一个文件,这时候如果最后一个Segment满了也不会roll出新的Segment,持续的将消息写入到最后一个Segment,所以这时候也会发生Segment的size大于配置的size的情况 
  125.         try
  126.             for (WriteRequest request : this.bufferQueue) { 
  127.                 final int remainning = request.buf.remaining(); 
  128.                 final long offset = last.start + last.fileMessageSet.append(request.buf); 
  129.                 if (request.cb != null) { 
  130.                     request.cb.appendComplete(Location.create(offset, remainning)); 
  131.                 } 
  132.             } 
  133.             this.bufferQueue.clear(); 
  134.         } catch (IOException e) { 
  135.             log.error("Append message failed", e); 
  136.         } 
  137.     } 
  138. …… 
  139.  
  140.      //Append多个消息,返回写入的位置 
  141.     public void append(final List<Long> msgIds, final List<PutCommand> putCmds, final AppendCallback cb) { 
  142.         this.appendBuffer(MessageUtils.makeMessageBuffer(msgIds, putCmds), cb); 
  143.     } 
  144.  
  145.     /**
  146.      * 重放事务操作,如果消息没有存储成功,则重新存储,并返回新的位置
  147.      */ 
  148.     public void replayAppend(final long offset, final int length, final int checksum, final List<Long> msgIds, 
  149.             final List<PutCommand> reqs, final AppendCallback cb) throws IOException { 
  150.        //如果消息没有存储,则重新存储,写到最后一个Segment尾部 
  151.         final Segment segment = this.findSegment(this.segments.view(), offset); 
  152.         if (segment == null) { 
  153.             this.append(msgIds, reqs, cb); 
  154.         } else
  155.             final MessageSet messageSet = segment.fileMessageSet.slice(offset - segment.start, offset - segment.start + length); 
  156.             final ByteBuffer buf = ByteBuffer.allocate(length); 
  157.             messageSet.read(buf, offset - segment.start); 
  158.             buf.flip(); 
  159.             final byte[] bytes = new byte[buf.remaining()]; 
  160.             buf.get(bytes); 
  161.             // 这个校验和是整个消息的校验和,这跟message的校验和不一样,注意区分 
  162.             final int checkSumInDisk = CheckSum.crc32(bytes); 
  163.             // 没有存入,则重新存储 
  164.             if (checksum != checkSumInDisk) { 
  165.                 this.append(msgIds, reqs, cb); 
  166.             } else
  167.                 // 正常存储了消息,无需处理 
  168.                 if (cb != null) {  
  169.                     this.notifyCallback(cb, null); 
  170.                 } 
  171.             } 
  172.         } 
  173.     } 
  174.  
  175. //判断是否需要roll,如果当前 messagestore最后一个segment的size>=配置的segment size,则产生新的segment,并将新的segment作为最后一个segment,原来最后的segment提交一次,并将mutable设置为false 
  176. private void mayBeRoll() throws IOException { 
  177.         if (this.segments.last().fileMessageSet.getSizeInBytes() >= this.metaConfig.getMaxSegmentSize()) { 
  178.             this.roll(); 
  179.         } 
  180.     } 
  181.  
  182.     String nameFromOffset(final long offset) { 
  183.         final NumberFormat nf = NumberFormat.getInstance(); 
  184.         nf.setMinimumIntegerDigits(20); 
  185.         nf.setMaximumFractionDigits(0); 
  186.         nf.setGroupingUsed(false); 
  187.         return nf.format(offset) + FILE_SUFFIX; 
  188.     } 
  189.  
  190. private long nextAppendOffset() throws IOException { 
  191.         final Segment last = this.segments.last(); 
  192.         last.fileMessageSet.flush(); 
  193.         return last.start + last.size(); 
  194.     } 
  195.  
  196.     private void roll() throws IOException { 
  197.         final long newOffset = this.nextAppendOffset(); 
  198.         //新的segment对应的存储文件的命名为原来最后一个segment的起始位置 + segment的size 
  199.         final File newFile = new File(this.partitionDir, this.nameFromOffset(newOffset)); 
  200.         this.segments.last().fileMessageSet.flush(); 
  201.         this.segments.last().fileMessageSet.setMutable(false); 
  202.         this.segments.append(new Segment(newOffset, newFile)); 
  203.     } 
  204.  
  205. //判断是否需要消息提交到磁盘,判断的条件有两个,如果达到组提交的条件或者达到间隔的提交时间 
  206. private void mayBeFlush(final int numOfMessages) throws IOException { 
  207.         if (this.unflushed.addAndGet(numOfMessages) > this.metaConfig.getTopicConfig(this.topic).getUnflushThreshold() 
  208.                 || SystemTimer.currentTimeMillis() - this.lastFlushTime.get() > this.metaConfig.getTopicConfig(this.topic).getUnflushInterval()) { 
  209.             this.flush0(); 
  210.         } 
  211.     } 
  212.  
  213. //提交到磁盘 
  214. public void flush() throws IOException { 
  215.         this.writeLock.lock(); 
  216.         try
  217.             this.flush0(); 
  218.         } finally
  219.             this.writeLock.unlock(); 
  220.         } 
  221.     } 
  222.  
  223.      
  224. private void flush0() throws IOException { 
  225.         if (this.useGroupCommit()) { 
  226.             return
  227.         } 
  228.         //由于只有最后一个segment是可变,即可写入消息的,所以只需要提交最后一个segment的消息 
  229.         this.segments.last().fileMessageSet.flush(); 
  230.         this.unflushed.set(0); 
  231.         this.lastFlushTime.set(SystemTimer.currentTimeMillis()); 
  232.     } 
  233.  
  234.  
  235. @Override 
  236.     public void close() throws IOException { 
  237.         this.closed = true
  238.         this.interrupt(); 
  239.      //等待子线程完成写完异步队列中剩余未写的消息 
  240.         try
  241.             this.join(500); 
  242.         } catch (InterruptedException e) { 
  243.             Thread.currentThread().interrupt(); 
  244.         } 
  245.       //关闭segment,保证内容都已经提交到磁盘 
  246.         for (final Segment segment : this.segments.view()) { 
  247.             segment.fileMessageSet.close(); 
  248.         } 
  249.     } 
  250.  
  251. //返回segment的信息,主要包括segment的开始位置以及 segment 的size 
  252. public List<SegmentInfo> getSegmentInfos() { 
  253.         final List<SegmentInfo> rt = new ArrayList<SegmentInfo>(); 
  254.         for (final Segment seg : this.segments.view()) { 
  255.             rt.add(new SegmentInfo(seg.start, seg.size())); 
  256.         } 
  257.         return rt; 
  258.     } 
  259.  
  260. /**
  261.      * 返回当前最大可读的offset
  262.      */ 
  263.   //需要注意的是,在文件缓存中的消息是不可读的,可以通过getSizeInBytes()方法来判断还有多少内容还在文件缓存中,getSizeInBytes()方法返回的值是包括所有在磁盘和缓存中的size 
  264.     public long getMaxOffset() { 
  265.         final Segment last = this.segments.last(); 
  266.         if (last != null) { 
  267.             return last.start + last.size(); 
  268.         } else
  269.             return 0
  270.         } 
  271.     } 
  272.  
  273.     /**
  274.      * 返回当前最小可读的offset
  275.      */ 
  276.     public long getMinOffset() { 
  277.         Segment first = this.segments.first(); 
  278.         if (first != null) { 
  279.             return first.start; 
  280.         } else
  281.             return 0
  282.         } 
  283.     } 
  284.  
  285. /**
  286.      * 根据offset和maxSize返回所在MessageSet, 当offset超过最大offset的时候返回null,
  287.      * 当offset小于最小offset的时候抛出ArrayIndexOutOfBounds异常
  288.      */ 
  289.   //代码的注释以及清楚的解析了作用 
  290.     public MessageSet slice(final long offset, final int maxSize) throws IOException { 
  291.         final Segment segment = this.findSegment(this.segments.view(), offset); 
  292.         if (segment == null) { 
  293.             return null
  294.         } else
  295.             return segment.fileMessageSet.slice(offset - segment.start, offset - segment.start + maxSize); 
  296.         } 
  297.     } 
  298.  
  299. /**
  300.      * 根据offset查找文件,如果超过尾部,则返回null,如果在头部之前,则抛出ArrayIndexOutOfBoundsException
  301.      */ 
  302.   //指定位置找到对应的segment,由于前面的文件组织方式,所以这里可以采用2分查找的方式, 
  303.   //效率很高 
  304.     Segment findSegment(final Segment[] segments, final long offset) { 
  305.         if (segments == null || segments.length < 1) { 
  306.             return null
  307.         } 
  308.         // 老的数据不存在,返回最近最老的数据 
  309.         final Segment last = segments[segments.length - 1]; 
  310.         // 在头部以前,抛出异常 
  311.         if (offset < segments[0].start) { 
  312.             throw new ArrayIndexOutOfBoundsException(); 
  313.         } 
  314.         // 刚好在尾部或者超出范围,返回null 
  315.         if (offset >= last.start + last.size()) { 
  316.             return null
  317.         } 
  318.         // 根据offset二分查找 
  319.         int low = 0
  320.         int high = segments.length - 1
  321.         while (low <= high) { 
  322.             final int mid = high + low >>> 1
  323.             final Segment found = segments[mid]; 
  324.             if (found.contains(offset)) { 
  325.                 return found; 
  326.             } else if (offset < found.start) { 
  327.                 high = mid - 1
  328.             } else
  329.                 low = mid + 1
  330.             } 
  331.         } 
  332.         return null
  333.     } 
//添加消息的方式有两种,同步和异步
	public void append(final long msgId, final PutCommand req, final AppendCallback cb) {
		//首先将内容包装成前面介绍过的消息存储格式
		this.appendBuffer(MessageUtils.makeMessageBuffer(msgId, req), cb);
	}
  //异步写入的包装类
	private static class WriteRequest {
		public final ByteBuffer buf;
		public final AppendCallback cb;
		public Location result;

		public WriteRequest(final ByteBuffer buf, final AppendCallback cb) {
			super();
			this.buf = buf;
			this.cb = cb;
		}
	}

  //这里比较好的设计是采用回调的方式来,对于异步写入实现就变得非常容易
 //AppendCallback返回的是消息成功写入的位置Location(起始位置和消息长度),该Location并不是相对于当前Segment的开始位置0,而是相对于当前Segment给定的值(对应文件命名值即为给定的值),以后查询消息的时候直接使用该位置就可以快速定位到消息写入到哪个文件
//这也就是为什么文件名的命名采用前后衔接的方式,这也通过2分查找可以快速定位消息的位置
	private void appendBuffer(final ByteBuffer buffer, final AppendCallback cb) {
		if (this.closed) {
			throw new IllegalStateException("Closed MessageStore.");
		}
		//如果启动异步写入并且消息长度小于一次提交的最大值maxTransferSize,则将该消息放入异步写入队列
		if (this.useGroupCommit() && buffer.remaining() < this.maxTransferSize) {
			this.bufferQueue.offer(new WriteRequest(buffer, cb));
		} else {
			Location location = null;
			final int remainning = buffer.remaining();
			this.writeLock.lock();
			try {
				final Segment cur = this.segments.last();
				final long offset = cur.start + cur.fileMessageSet.append(buffer);
				this.mayBeFlush(1);
				this.mayBeRoll();
				location = Location.create(offset, remainning);
			} catch (final IOException e) {
				log.error("Append file failed", e);
				location = Location.InvalidLocaltion;
			} finally {
				this.writeLock.unlock();
				if (cb != null) {
					cb.appendComplete(location);
				}
				//调用回调方法,数据写入文件缓存
			}
		}
	}

……

  //判断是否启用异步写入,如果设置为unflushThreshold <=0的数字,则认为启动异步写入;如果设置为unflushThreshold =1,则是同步写入,即每写入一个消息都会提交到磁盘;如果unflushThreshold>0,则是依赖组提交或者是超时提交
	private boolean useGroupCommit() {
		return this.unflushThreshold <= 0;
	}

	@Override
	public void run() {
		// 等待force的队列
		final LinkedList<WriteRequest> toFlush = new LinkedList<WriteRequest>();
		WriteRequest req = null;
		long lastFlushPos = 0;
		Segment last = null;
		//存储没有关闭并且线程没有被中断
		while (!this.closed && !Thread.currentThread().isInterrupted()) {
			try {
				if (last == null) {
					//获取最后的一个segment,将消息写入最后segment对应的文件
					last = this.segments.last();
					lastFlushPos = last.fileMessageSet.highWaterMark();
				}
				if (req == null) {
                     //如果等待提交到磁盘的队列toFlush为空,则两种可能:一、刚刚提交完,列表为空;二、等待写入消息的队列为空,如果判断toFlush,则调用bufferQueue.take()方法,可以阻塞住队列,而如果toFlush不为空,则调用bufferQueue.poll,这是提高性能的一种做法。
					if (toFlush.isEmpty()) {
						req = this.bufferQueue.take();
					} else {
						req = this.bufferQueue.poll();
						//如果当前请求为空,表明等待写入的消息已经没有了,这时候文件缓存中的消息需要提交到磁盘,防止消息丢失;或者如果已经写入文件的大小大于maxTransferSize,则提交到磁盘
                          //这里需要注意的是,会出现这样一种情况,刚好最后一个segment的文件快满了,这时候是不会roll出一个新的segment写入消息的,而是直接追加到原来的segment尾部,可能导致segment对应的文件大小大于配置的单个segment大小
						if (req == null || last.fileMessageSet.getSizeInBytes() > lastFlushPos + this.maxTransferSize) {
							// 强制force,确保内容保存到磁盘
							last.fileMessageSet.flush();
							lastFlushPos = last.fileMessageSet.highWaterMark();
							// 通知回调
							//异步写入比组写入可靠,因为异步写入一定是提交到磁盘的时候才进行回调的,而组写入如果依赖组提交的方式,则可能会丢失数据,因为组写入在消息写入到文件缓存的时候就进行回调了(除非设置unflushThreshold=1)
							for (final WriteRequest request : toFlush) {
								request.cb.appendComplete(request.result);
							}
							toFlush.clear();
							// 是否需要roll
							this.mayBeRoll();
							// 如果切换文件,重新获取last
							if (this.segments.last() != last) {
								last = null;
							}
							continue;
						}
					}
				}

				if (req == null) {
					continue;
				}
				//写入文件,并计算写入位置
				final int remainning = req.buf.remaining();
				//写入位置为:当前segment给定的值 + 加上文件已有的长度 
final long offset = last.start + last.fileMessageSet.append(req.buf);
				req.result = Location.create(offset, remainning);
				if (req.cb != null) {
					toFlush.add(req);
				}
				req = null;
			} catch (final IOException e) {
				log.error("Append message failed,*critical error*,the group commit thread would be terminated.", e);
				// TODO io异常没办法处理了,简单跳出?
				break;
			} catch (final InterruptedException e) {
				// ignore
			}
		}
		// terminated
		//关闭store 前,将等待写入队列中的剩余消息写入最后一个文件,这时候如果最后一个Segment满了也不会roll出新的Segment,持续的将消息写入到最后一个Segment,所以这时候也会发生Segment的size大于配置的size的情况
		try {
			for (WriteRequest request : this.bufferQueue) {
				final int remainning = request.buf.remaining();
				final long offset = last.start + last.fileMessageSet.append(request.buf);
				if (request.cb != null) {
					request.cb.appendComplete(Location.create(offset, remainning));
				}
			}
			this.bufferQueue.clear();
		} catch (IOException e) {
			log.error("Append message failed", e);
		}
	}
……

	 //Append多个消息,返回写入的位置
	public void append(final List<Long> msgIds, final List<PutCommand> putCmds, final AppendCallback cb) {
		this.appendBuffer(MessageUtils.makeMessageBuffer(msgIds, putCmds), cb);
	}

	/**
	 * 重放事务操作,如果消息没有存储成功,则重新存储,并返回新的位置
	 */
	public void replayAppend(final long offset, final int length, final int checksum, final List<Long> msgIds,
			final List<PutCommand> reqs, final AppendCallback cb) throws IOException {
       //如果消息没有存储,则重新存储,写到最后一个Segment尾部
		final Segment segment = this.findSegment(this.segments.view(), offset);
		if (segment == null) {
			this.append(msgIds, reqs, cb);
		} else {
			final MessageSet messageSet = segment.fileMessageSet.slice(offset - segment.start, offset - segment.start + length);
			final ByteBuffer buf = ByteBuffer.allocate(length);
			messageSet.read(buf, offset - segment.start);
			buf.flip();
			final byte[] bytes = new byte[buf.remaining()];
			buf.get(bytes);
			// 这个校验和是整个消息的校验和,这跟message的校验和不一样,注意区分
			final int checkSumInDisk = CheckSum.crc32(bytes);
			// 没有存入,则重新存储
			if (checksum != checkSumInDisk) {
				this.append(msgIds, reqs, cb);
			} else {
				// 正常存储了消息,无需处理
				if (cb != null) { 
					this.notifyCallback(cb, null);
				}
			}
		}
	}

//判断是否需要roll,如果当前 messagestore最后一个segment的size>=配置的segment size,则产生新的segment,并将新的segment作为最后一个segment,原来最后的segment提交一次,并将mutable设置为false
private void mayBeRoll() throws IOException {
		if (this.segments.last().fileMessageSet.getSizeInBytes() >= this.metaConfig.getMaxSegmentSize()) {
			this.roll();
		}
	}

	String nameFromOffset(final long offset) {
		final NumberFormat nf = NumberFormat.getInstance();
		nf.setMinimumIntegerDigits(20);
		nf.setMaximumFractionDigits(0);
		nf.setGroupingUsed(false);
		return nf.format(offset) + FILE_SUFFIX;
	}

private long nextAppendOffset() throws IOException {
		final Segment last = this.segments.last();
		last.fileMessageSet.flush();
		return last.start + last.size();
	}

	private void roll() throws IOException {
		final long newOffset = this.nextAppendOffset();
		//新的segment对应的存储文件的命名为原来最后一个segment的起始位置 + segment的size
		final File newFile = new File(this.partitionDir, this.nameFromOffset(newOffset));
		this.segments.last().fileMessageSet.flush();
		this.segments.last().fileMessageSet.setMutable(false);
		this.segments.append(new Segment(newOffset, newFile));
	}

//判断是否需要消息提交到磁盘,判断的条件有两个,如果达到组提交的条件或者达到间隔的提交时间
private void mayBeFlush(final int numOfMessages) throws IOException {
		if (this.unflushed.addAndGet(numOfMessages) > this.metaConfig.getTopicConfig(this.topic).getUnflushThreshold()
				|| SystemTimer.currentTimeMillis() - this.lastFlushTime.get() > this.metaConfig.getTopicConfig(this.topic).getUnflushInterval()) {
			this.flush0();
		}
	}

//提交到磁盘
public void flush() throws IOException {
		this.writeLock.lock();
		try {
			this.flush0();
		} finally {
			this.writeLock.unlock();
		}
	}

	
private void flush0() throws IOException {
		if (this.useGroupCommit()) {
			return;
		}
		//由于只有最后一个segment是可变,即可写入消息的,所以只需要提交最后一个segment的消息
		this.segments.last().fileMessageSet.flush();
		this.unflushed.set(0);
		this.lastFlushTime.set(SystemTimer.currentTimeMillis());
	}


@Override
	public void close() throws IOException {
		this.closed = true;
		this.interrupt();
     //等待子线程完成写完异步队列中剩余未写的消息
		try {
			this.join(500);
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
		}
      //关闭segment,保证内容都已经提交到磁盘
		for (final Segment segment : this.segments.view()) {
			segment.fileMessageSet.close();
		}
	}

//返回segment的信息,主要包括segment的开始位置以及 segment 的size
public List<SegmentInfo> getSegmentInfos() {
		final List<SegmentInfo> rt = new ArrayList<SegmentInfo>();
		for (final Segment seg : this.segments.view()) {
			rt.add(new SegmentInfo(seg.start, seg.size()));
		}
		return rt;
	}

/**
	 * 返回当前最大可读的offset
	 */
  //需要注意的是,在文件缓存中的消息是不可读的,可以通过getSizeInBytes()方法来判断还有多少内容还在文件缓存中,getSizeInBytes()方法返回的值是包括所有在磁盘和缓存中的size
	public long getMaxOffset() {
		final Segment last = this.segments.last();
		if (last != null) {
			return last.start + last.size();
		} else {
			return 0;
		}
	}

	/**
	 * 返回当前最小可读的offset
	 */
	public long getMinOffset() {
		Segment first = this.segments.first();
		if (first != null) {
			return first.start;
		} else {
			return 0;
		}
	}

/**
	 * 根据offset和maxSize返回所在MessageSet, 当offset超过最大offset的时候返回null,
	 * 当offset小于最小offset的时候抛出ArrayIndexOutOfBounds异常
	 */
  //代码的注释以及清楚的解析了作用
	public MessageSet slice(final long offset, final int maxSize) throws IOException {
		final Segment segment = this.findSegment(this.segments.view(), offset);
		if (segment == null) {
			return null;
		} else {
			return segment.fileMessageSet.slice(offset - segment.start, offset - segment.start + maxSize);
		}
	}

/**
	 * 根据offset查找文件,如果超过尾部,则返回null,如果在头部之前,则抛出ArrayIndexOutOfBoundsException
	 */
  //指定位置找到对应的segment,由于前面的文件组织方式,所以这里可以采用2分查找的方式,
  //效率很高
	Segment findSegment(final Segment[] segments, final long offset) {
		if (segments == null || segments.length < 1) {
			return null;
		}
		// 老的数据不存在,返回最近最老的数据
		final Segment last = segments[segments.length - 1];
		// 在头部以前,抛出异常
		if (offset < segments[0].start) {
			throw new ArrayIndexOutOfBoundsException();
		}
		// 刚好在尾部或者超出范围,返回null
		if (offset >= last.start + last.size()) {
			return null;
		}
		// 根据offset二分查找
		int low = 0;
		int high = segments.length - 1;
		while (low <= high) {
			final int mid = high + low >>> 1;
			final Segment found = segments[mid];
			if (found.contains(offset)) {
				return found;
			} else if (offset < found.start) {
				high = mid - 1;
			} else {
				low = mid + 1;
			}
		}
		return null;
	}

未完待续,下篇介绍存储模块的文件删除策略

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值