代码拉取完成,页面将自动刷新
package leveldb
import (
"fmt"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/util"
"sync"
)
var records = make(map[string]*Level)
var mutex sync.RWMutex
func Create(name, path string) error {
mutex.Lock()
defer mutex.Unlock()
if _, ok := records[name]; ok {
return fmt.Errorf("Exist %s", name)
}
db, err := leveldb.OpenFile(path, nil)
if err != nil {
panic(err)
}
records[name] = &Level{db: db}
return nil
}
type Level struct {
db *leveldb.DB
}
type Model struct {
Key []byte
Val []byte
}
func (l *Level) Insert(obj Model) error {
return l.db.Put(obj.Key, obj.Val, nil)
}
func (l *Level) InsertList(list []Model) error {
batch := new(leveldb.Batch)
for _, v := range list {
batch.Put(v.Key, v.Val)
}
return l.db.Write(batch, nil)
}
func (l *Level) Del(key []byte) error {
return l.db.Delete(key, nil)
}
func (l *Level) DelList(keyList [][]byte) error {
for _, key := range keyList {
err := l.db.Delete(key, nil)
if err != nil {
return err
}
}
return nil
}
func (l *Level) Get(key []byte) (obj Model, err error) {
obj.Key = key
obj.Val, err = l.db.Get(key, nil)
return obj, err
}
func (l *Level) Find(key [][]byte) (list []Model, err error) {
list = make([]Model, 0)
for _, v := range key {
val, err := l.db.Get(v, nil)
if err != nil {
return list, err
}
if len(val) > 0 {
list = append(list, Model{Key: v, Val: val})
}
}
return list, nil
}
func (l *Level) GetAll() (list []Model, err error) {
list = make([]Model, 0)
iter := l.db.NewIterator(nil, nil)
for iter.Next() {
list = append(list, Model{Key: iter.Key(), Val: iter.Value()})
}
iter.Release()
err = iter.Error()
return list, err
}
func (l *Level) FindKey(key []byte) (list []Model, err error) {
list = make([]Model, 0)
iter := l.db.NewIterator(util.BytesPrefix(key), nil)
for iter.Next() {
list = append(list, Model{Key: iter.Key(), Val: iter.Value()})
}
iter.Release()
err = iter.Error()
return list, err
}
func (l *Level) FindRange(start, end []byte) (list []Model, err error) {
list = make([]Model, 0)
iter := l.db.NewIterator(&util.Range{Start: start, Limit: end}, nil)
for iter.Next() {
list = append(list, Model{Key: iter.Key(), Val: iter.Value()})
}
iter.Release()
err = iter.Error()
return list, err
}
func (l *Level) FindSeek(seek []byte) (list []Model, err error) {
list = make([]Model, 0)
iter := l.db.NewIterator(nil, nil)
for ok := iter.Seek(seek); ok; ok = iter.Next() {
list = append(list, Model{Key: iter.Key(), Val: iter.Value()})
}
iter.Release()
err = iter.Error()
return list, err
}
func Get(name string) *Level {
mutex.RLock()
m, ok := records[name]
mutex.RUnlock()
if !ok {
return nil
}
return m
}
func Close(name string) {
mutex.RLock()
m, ok := records[name]
delete(records, name)
mutex.RUnlock()
if !ok {
return
}
m.db.Close()
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。