当前位置:   article > 正文

kafka日志存储(四):OffsetIndex

offsetindex

为了提高查找消息的性能,kafka在0.8 后为每个日志文件添加了对应的索引文件,OffsetIndex对象对应管理磁盘上的一个索引文件,预FileMessageSet共同构成了一个LogSegment对象。
OffsetIndex字段有:

  1. class OffsetIndex(@volatile private[this]
  2. //指向磁盘上的索引文件。
  3. var _file: File,
  4. // 日志文件中的第一个消息的offset
  5. val baseOffset: Long,
  6. val maxIndexSize: Int = -1) extends Logging {
  7. //mmap用来操作索引文件
  8. private[this] var mmap: MappedByteBuffer = {
  9. //如果索引文件不存在,则创建新文件并返回true
  10. val newlyCreated = _file.createNewFile()
  11. val raf = new RandomAccessFile(_file, "rw")
  12. try {
  13. /* 对新创建的索引文件进行扩容 */
  14. if (newlyCreated) {
  15. if (maxIndexSize < 8)
  16. throw new IllegalArgumentException("Invalid max index size: " + maxIndexSize)
  17. //根据maxIndexSize的值对索引文件进行扩容,扩容结果是小于maxIndexSize的最大的8的倍数
  18. raf.setLength(roundToExactMultiple(maxIndexSize, 8))
  19. }
  20. /* 内存映射 */
  21. val len = raf.length()
  22. val idx = raf.getChannel.map(FileChannel.MapMode.READ_WRITE, 0, len)
  23. /* set the position in the index for the next entry */
  24. if (newlyCreated)
  25. idx.position(0)
  26. else
  27. // if this is a pre-existing index, assume it is all valid and set position to last entry
  28. idx.position(roundToExactMultiple(idx.limit, 8))
  29. idx
  30. } finally {
  31. CoreUtils.swallow(raf.close())
  32. }
  33. }
  34. /* 索引文件中索引项的个数 */
  35. @volatile
  36. private[this] var _entries = mmap.position / 8
  37. /* 最大索引个数 */
  38. @volatile
  39. private[this] var _maxEntries = mmap.limit / 8
  40. //最后一个索引的offset
  41. @volatile
  42. private[this] var _lastOffset = readLastEntry.offset
  43. }

offsetIndex中最常用的是查找方法lockup

  1. def lookup(targetOffset: Long): OffsetPosition = {
  2. maybeLock(lock) {
  3. val idx = mmap.duplicate
  4. //二分查找
  5. val slot = indexSlotFor(idx, targetOffset)
  6. if(slot == -1)
  7. OffsetPosition(baseOffset, 0)
  8. else
  9. OffsetPosition(baseOffset + relativeOffset(idx, slot), physical(idx, slot))
  10. }
  11. }

 

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

闽ICP备14008679号