Loading

RocketMQ的Index File

RocketMQ的Index File

Index File由三部分组成:Index Head、Hash Slot、Index Item

image-20220105114057010

Index Item的结构

image-20220105114618351
看完这两个没概念?没事,有个印象就好,重点看下面索引的生成

索引的生成

  1. 插入一条消息
  2. 计算出消息key的hashcode
  3. 根据hashcode%500w,计算出应该放到哪个槽中
  4. 然后在插入Index Item,并在槽中记录Index Item的位置

假设hash slot只有5个、index item 只有20个,演示一下插入索引的过程

image-20220105114234443

插入key1, 计算出hashcode=5,5%5=0在hashslot的0位置

在index item list中插入一个Index Item

hashslot 0位置指向插入的Index item

image-20220105114256125

插入key2, 计算出hashcode=7,7%5=2在hashslot的0位置

在index item list中插入一个Index Item

hashslot 2位置指向插入的Index item

image-20220105114331042

插入key3, 计算出hashcode=10,10%5=0在hashslot的0位置

此时发生了hash碰撞,它在slot的位置和key1相同,怎么处理?

在index item list中插入一个Index Item

hashslot 0位置指向插入的Index item key3

image-20220105114357489

那key1岂不是变成一个孤岛了?

Index item key3会将它的preIndexNo指向Index item key1,这样index item key3和index item key1形成了一个单向链表

image-20220105114426898

索引查找

假设要查询的key是key1

  1. 根据key计算出所在hash槽,计算出位置是0

  2. 根据hash槽的值定位对应的Index item, 定位到key3的index item,它是一个单向链表,key3 -> key1

  3. 遍历这个链表,定位到key1

  4. 根据item的pyhoffset,到commitLog中定位到消息

Index Head

  • beginTimestamp:文件中消息的最小存储时间

  • endTimestamp:文件中消息的最大存储时间

  • beginPhyoffset:消息的最小偏移量

  • endphyoffset:消息的最大物理偏移量

  • hashSlotCount:已用 hash 槽个数

  • indexCount:已用 index 个数

posted @ 2022-01-05 11:51  树先生1024  阅读(146)  评论(0编辑  收藏  举报