goleveldb iter 会创建快照,删除数据库内容后不影响当前迭代器。
测试代码:
func NewDBInstance(dbPath string) *leveldb.DB {
db, err := leveldb.OpenFile(dbPath, nil)
if err != nil {
log.Fatal(err)
}
return db
}
func TestLeveldb(t *testing.T) {
db := NewDBInstance("./test.db")
db.Put([]byte("hello"), []byte("world"), nil)
db.Put([]byte("hello1"), []byte("world1"), nil)
db.Put([]byte("hello2"), []byte("world2"), nil)
db.Put([]byte("hello3"), []byte("world3"), nil)
db.Put([]byte("hello4"), []byte("world4"), nil)
db.Put([]byte("hello5"), []byte("world5"), nil)
iter := db.NewIterator(nil, nil)
for iter.Next() {
fmt.Println("删除前:", string(iter.Key()), string(iter.Value()))
db.Delete(iter.Key(), nil)
fmt.Println("删除后:", string(iter.Key()), string(iter.Value()))
}
for iter.Prev() {
fmt.Println("倒序遍历:", string(iter.Key()), string(iter.Value()))
}
iter2 := db.NewIterator(nil, nil)
for iter2.Next() {
fmt.Println("iter2 :", string(iter.Key()), string(iter.Value()))
}
for iter.Next() {
fmt.Println("iter1 :", string(iter.Key()), string(iter.Value()))
}
}
测试结果