boltdb的使用

Bolt is a pure Go key/value store inspired by Howard Chu’s LMDB project. The goal of the project is to provide a simple, fast, and reliable database for projects that don’t require a full database server such as Postgres or MySQL.

bolt 是一个简单的kv数据库,使用及其简单,目前github项目处于只读状态。

数据库连接

package main

import (
	"log"

	"github.com/boltdb/bolt"
)

func main() {
	// 文件不存在,会新建文件
	db, err := bolt.Open("sai.db", 0600, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	...
}

事务

// 读写
err := db.Update(func(tx *bolt.Tx) error {
	...
	return nil
})

// 只读,里面只能进行读取操作
err := db.View(func(tx *bolt.Tx) error {
	...
	return nil
})

常用操作

// 创建一个bucket,可以理解成一个table
b, _ := tx.CreateBucketIfNotExists([]byte("sai0556"))
// 新增
b.Put([]byte("a"), []byte("11"))
b.Put([]byte("b"), []byte("22"))

// 取
v := b.Get([]byte("a"))
fmt.Printf("The a is: %s\n", v)

// 删除
b.Delete([]byte("a"))

// 游标遍历
/*
First()  Move to the first key.
Last()   Move to the last key.
Seek()   Move to a specific key.
Next()   Move to the next key.
Prev()   Move to the previous key
*/
c := b.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
    fmt.Printf("key=%s, value=%s\n", k, v)
}

// ForEach 遍历
b.ForEach(func(k, v []byte) error {
    fmt.Printf("key=%s, value=%s\n", k, v)
    return nil
})

// 删除bucket
tx.DeleteBucket([]byte("sai0556"))

使用很简单,但需要注意以下几点:

  • 只读View中,不能使用编辑、删除、新增等写操作,会产生错误
  • 因为底层使用了读写锁,进行写操作,要尽可能快,更不要开启长事务,会造成阻塞,影响性能

更多说明可参考:


boltdb的使用
https://blog.puresai.com/2021/08/08/361/
作者
puresai
许可协议