badger数据库示例用法
2020-09-22 本文已影响0人
池边树下
package main
import (
"fmt"
"log"
"time"
badger "github.com/dgraph-io/badger/v2"
)
func main() {
// opt := badger.DefaultOptions("").WithInMemory(true) // 内存模式/无盘模式
db, err := badger.Open(badger.DefaultOptions("./data"))
if err != nil {
log.Fatal(err)
}
defer db.Close()
// 读写
err = db.Update(func(txn *badger.Txn) error {
err := txn.Set([]byte("answer"), []byte("42"))
return err
})
// 只读
err = db.View(func(txn *badger.Txn) error {
item, err := txn.Get([]byte("answer"))
if err != nil {
log.Fatal(err)
}
var valNot, valCopy []byte
err = item.Value(func(val []byte) error {
// This func with val would only be called if item.Value encounters no error.
// Accessing val here is valid.
fmt.Printf("The answer is: %s\n", val)
// Copying or parsing val is valid.
valCopy = append([]byte{}, val...)
// Assigning val slice to another variable is NOT OK.
valNot = val // Do not do this.
return nil
})
if err != nil {
log.Fatal(err)
}
// DO NOT access val here. It is the most common cause of bugs.
fmt.Printf("NEVER do this. %s\n", valNot)
// You must copy it to use it outside item.Value(...).
fmt.Printf("The answer is: %s\n", valCopy)
// Alternatively, you could also use item.ValueCopy().
valCopy, err = item.ValueCopy(nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("The answer is: %s\n", valCopy)
return nil
})
// 允许在键上设置可选的生存时间(TTL)值。一旦TTL失效,该密钥将不再可检索,并且可以进行垃圾回收。可以time.Duration使用Entry.WithTTL() 和Txn.SetEntry()API方法将TTL设置为值。
err = db.Update(func(txn *badger.Txn) error {
e := badger.NewEntry([]byte("answer"), []byte("42")).WithTTL(time.Hour)
err := txn.SetEntry(e)
return err
})
if err != nil {
log.Fatal(err)
}
// 遍历键
err = db.View(func(txn *badger.Txn) error {
opts := badger.DefaultIteratorOptions
opts.PrefetchSize = 10
it := txn.NewIterator(opts)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
k := item.Key()
err := item.Value(func(v []byte) error {
fmt.Printf("key=%s, value=%s\n", k, v)
return nil
})
if err != nil {
return err
}
}
return nil
})
if err != nil {
log.Fatal(err)
}
// 垃圾收集
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
for range ticker.C {
again:
err := db.RunValueLogGC(0.7)
if err == nil {
goto again
}
}
}