什么是 rebolt?
go get github.com/mediocregopher/radix.v2/...
写入一个key-value键值对:
mydb.Update(func(tx rebolt.ITX) error {
key, value := []byte("hello"), []byte("world")
tx.Set(key, value)
return nil
})
mydb.Update(func(tx rebolt.ITX) error {
key, value := []byte("hello"), []byte("world")
tx.HSet("hash-name", key, value)
return nil
})
var members [][]byte
mydb.View(func(tx rebolt.ITX) error {
key := []byte("hello")
members = tx.SMembers("myset", key)
return nil
})
//print members
for _, m := range members {
log.Printf("%s,", string(m))
}
//一个进程只需要InitDB一次
rebolt.InitDB(rebolt.Config{
BoltConf: &rebolt.BoltConfig{
DBPath: "mybolt.db",
},
RedisConf: &rebolt.RedisConfig{
Network: "tcp",
Addr: "localhost:6379",
PoolSize: 2,
},
})
// GetDB随用随取,自动管理的,不用手动释放
mydb, err := GetDB("redis", 0)
if err != nil {
panic(err)
}
mydb.Update(func(tx rebolt.ITX) error {
key, value := []byte("hello"), []byte("world")
tx.Set(key, value)
if bytes.Compare(value, tx.Get(key)) != 0 {
return errors.New("gotten wrong value!");
}
return nil
})
详细接口说明见 godoc:
rebolt 是 redis 和 bolt 的合成词。 它封装了对redis和bolt这两个数据库的操作,提供了一个公共的、简单到死的、统一的操作层。
它结合了redis和bolt两个数据库的优点,借鉴了bolt的接口设计,并且也能让boltdb享受到redis的结构化数据的封装,同时你也能享受到使用类API的方式使用redis。
通过这个操作层,你能轻而易举的在redis和bolt之间切换。
repo: https://github.com/jibuji/rebolt
获取go get github.com/jibuji/rebolt
依赖下面两个库:go get github.com/mediocregopher/radix.v2/...
go get github.com/boltdb/bolt/...
不废话了,直接上例子:写入一个key-value键值对:
mydb.Update(func(tx rebolt.ITX) error {
key, value := []byte("hello"), []byte("world")
tx.Set(key, value)
return nil
})
so easy!
把键值对写入一个指定的hash表, 类似redis的 HSET key field value:mydb.Update(func(tx rebolt.ITX) error {
key, value := []byte("hello"), []byte("world")
tx.HSet("hash-name", key, value)
return nil
})
so easy, too!
读取一个Set的所有成员, 类似redis的 SMEMBERS key:var members [][]byte
mydb.View(func(tx rebolt.ITX) error {
key := []byte("hello")
members = tx.SMembers("myset", key)
return nil
})
//print members
for _, m := range members {
log.Printf("%s,", string(m))
}
so easy, too too! right?
注意:你可能已经发现了,上面有的用Update, 有的用View,Update是用来向数据库写入数据时用的,View是当只是读取数据时用的。当然也可以在Update中做读取操作,但当你的操作只和读取有关时,请使用View。
这是因为,当你使用bolt作为底层DB时,只读的事务可以和只读的事务并发,而写入操作是独占的,Update是读写事务,View是只读事务,所以当你只有只读操作时,使用View会更有效率。
一个完整点的例子://一个进程只需要InitDB一次
rebolt.InitDB(rebolt.Config{
BoltConf: &rebolt.BoltConfig{
DBPath: "mybolt.db",
},
RedisConf: &rebolt.RedisConfig{
Network: "tcp",
Addr: "localhost:6379",
PoolSize: 2,
},
})
// GetDB随用随取,自动管理的,不用手动释放
mydb, err := GetDB("redis", 0)
if err != nil {
panic(err)
}
mydb.Update(func(tx rebolt.ITX) error {
key, value := []byte("hello"), []byte("world")
tx.Set(key, value)
if bytes.Compare(value, tx.Get(key)) != 0 {
return errors.New("gotten wrong value!");
}
return nil
})
详细接口说明见 godoc:
https://godoc.org/github.com/jibuji/rebolt
博主私人博客http://jipengfei.com