LevelDB入門
LevelDB是Google開源的持久化KV單機(jī)數(shù)據(jù)庫关筒,具有很高的隨機(jī)寫趴捅,順序讀/寫性能紊搪,但是隨機(jī)讀的性能很一般
也就是說贪嫂,LevelDB很適合應(yīng)用在查詢較少,而寫很多的場景
key和value都是任意長度的字節(jié)數(shù)組
entry(即一條K-V記錄)默認(rèn)是按照key的字典順序存儲的祠够,當(dāng)然開發(fā)者也可以重載這個排序函數(shù)
提供的基本操作接口:Put()压汪、Delete()、Get()古瓤、Batch()
支持批量操作以原子操作進(jìn)行
可以創(chuàng)建數(shù)據(jù)全景的snapshot(快照)止剖,并允許在快照中查找數(shù)據(jù)
可以通過前向(或后向)迭代器遍歷數(shù)據(jù)(迭代器會隱含的創(chuàng)建一個snapshot)
自動使用Snappy壓縮數(shù)據(jù)
非關(guān)系型數(shù)據(jù)模型(NoSQL),不支持sql語句落君,也不支持索引
一次只允許一個進(jìn)程訪問一個特定的數(shù)據(jù)庫
沒有內(nèi)置的C/S架構(gòu)穿香,但開發(fā)者可以使用LevelDB庫自己封裝一個server
代碼
https://github.com/fengchunjian/goexamples/tree/master/goleveldb
//goleveldb.go
package main
import (
"fmt"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/util"
"strconv"
)
func main() {
//創(chuàng)建并打開數(shù)據(jù)庫
db, err := leveldb.OpenFile("./db", nil)
if err != nil {
panic(err)
}
defer db.Close() //關(guān)閉數(shù)據(jù)庫
//寫入5條數(shù)據(jù)
db.Put([]byte("key1"), []byte("value1"), nil)
db.Put([]byte("key2"), []byte("value2"), nil)
db.Put([]byte("key3"), []byte("value3"), nil)
db.Put([]byte("key4"), []byte("value4"), nil)
db.Put([]byte("key5"), []byte("value5"), nil)
//循環(huán)遍歷數(shù)據(jù)
fmt.Println("循環(huán)遍歷數(shù)據(jù)")
iter := db.NewIterator(nil, nil)
for iter.Next() {
fmt.Printf("key:%s, value:%s\n", iter.Key(), iter.Value())
}
iter.Release()
//讀取某條數(shù)據(jù)
data, _ := db.Get([]byte("key2"), nil)
fmt.Printf("讀取單條數(shù)據(jù)key2:%s\n", data)
//批量寫入數(shù)據(jù)
batch := new(leveldb.Batch)
batch.Put([]byte("key6"), []byte(strconv.Itoa(10000)))
batch.Put([]byte("key7"), []byte(strconv.Itoa(20000)))
batch.Delete([]byte("key4"))
db.Write(batch, nil)
//查找數(shù)據(jù)
key := "key7"
iter = db.NewIterator(nil, nil)
for ok := iter.Seek([]byte(key)); ok; ok = iter.Next() {
fmt.Printf("查找數(shù)據(jù):%s, value:%s\n", iter.Key(), iter.Value())
}
iter.Release()
//按key范圍遍歷數(shù)據(jù)
fmt.Println("按key范圍遍歷數(shù)據(jù)")
iter = db.NewIterator(&util.Range{Start: []byte("key3"), Limit: []byte("key7")}, nil)
for iter.Next() {
fmt.Printf("key:%s, value:%s\n", iter.Key(), iter.Value())
}
iter.Release()
}
編譯運(yùn)行
go get github.com/syndtr/goleveldb/leveldb
go build goleveldb.go
./goleveldb
循環(huán)遍歷數(shù)據(jù)
key:key1, value:value1
key:key2, value:value2
key:key3, value:value3
key:key4, value:value4
key:key5, value:value5
讀取單條數(shù)據(jù)key2:value2
查找數(shù)據(jù):key7, value:20000
按key范圍遍歷數(shù)據(jù)
key:key3, value:value3
key:key5, value:value5
key:key6, value:10000
參考文檔
Golang 之 key-value LevelDB
http://www.cnblogs.com/qufo/p/5701237.html
This is an implementation of the LevelDB key/value database in the Go programming language.
https://github.com/syndtr/goleveldb
LevelDB詳解
http://blog.csdn.net/linuxheik/article/details/52768223