BitcaskDB
codeflysafe Lv5

Bitcask 介绍

Bitcask

设计方案

Entry

1
2
3
4
5
6
7
type Entry struct {
Key []byte
KeySize uint32 // key 的长度
Value []byte
ValueSize uint32 // value 长度
Mark uint16 // 标记,是否删除
}

固定大小为 4 + 4 + 2

db_file

将一个文件作为持久化存储介质

1
2
3
4
type DBFile struct {
File *os.File // 存储的文件∏
OffSet int64 // 当前的偏移量
}

DB

1
2
3
4
5
6
7
8
9
10
11
// 数据库的定义
type BitcaskDB struct {
io.Closer
indexes map[string]int64 // key 与 offset 的索引
indexes2 map[string]int64 // merge 过程中使用的hash 表
dbFile *DBFile // 数据文件
dirPath string // 数据位置
mu sync.RWMutex // 采用读写锁
ratio int64 // indexes2, 新建时的大小
count int64
}

Get

首先从内存的indexes中根据key获取offset,即指向value的地址,然后去文件中读取

Write

采用文件的追加写即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 顺序写,写入Entry
func (f *DBFile) Write(e *Entry) (offset int64, err error) {
buf, err := e.Encode()
if err != nil {
return
}
_, err = f.File.WriteAt(buf, f.OffSet)
if err != nil {
return
}
offset = f.OffSet
f.OffSet += e.GetSize()
return
}

DEL

del 操作是一种特殊的读写,实现采用的是写入一条特殊的删除记录

1
_, err = db.dbFile.Write(NewEntry(key, nil, DEL))

Merge

采用生产者和消费者模式,使用channel作为通信媒介
从旧的文件中生成 entry, 写到新的文件中去

  • 本文标题:BitcaskDB
  • 本文作者:codeflysafe
  • 创建时间:2022-04-09 16:50:13
  • 本文链接:https://codeflysafe.github.io/2022/04/09/BitcaskDB/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
 评论