1
0
mirror of https://github.com/Mrs4s/go-cqhttp.git synced 2025-05-04 11:07:39 +08:00

cache: switch to leveldb

This commit is contained in:
wdvxdr 2022-08-31 21:07:18 +08:00
parent 96e6397636
commit 2f92146092
2 changed files with 15 additions and 59 deletions

View File

@ -2,14 +2,9 @@
package cache
import (
"fmt"
"sync"
log "github.com/sirupsen/logrus"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/internal/base"
"github.com/Mrs4s/go-cqhttp/internal/btree"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/opt"
)
// Media Cache DBs
@ -21,70 +16,36 @@ var (
// Cache wraps the btree.DB for concurrent safe
type Cache struct {
lock sync.RWMutex
db *btree.DB
ldb *leveldb.DB
}
// Insert 添加媒体缓存
func (c *Cache) Insert(md5, data []byte) {
c.lock.Lock()
defer c.lock.Unlock()
var hash [16]byte
copy(hash[:], md5)
c.db.Insert(&hash[0], data)
_ = c.ldb.Put(md5, data, nil)
}
// Get 获取缓存信息
func (c *Cache) Get(md5 []byte) []byte {
c.lock.RLock()
defer c.lock.RUnlock()
var hash [16]byte
copy(hash[:], md5)
return c.db.Get(&hash[0])
got, _ := c.ldb.Get(md5, nil)
return got
}
// Delete 删除指定缓存
func (c *Cache) Delete(md5 []byte) {
c.lock.Lock()
defer c.lock.Unlock()
var hash [16]byte
copy(hash[:], md5)
_ = c.db.Delete(&hash[0])
_ = c.ldb.Delete(md5, nil)
}
// Init 初始化 Cache
func Init() {
node, ok := base.Database["cache"]
var conf map[string]string
if ok {
err := node.Decode(&conf)
open := func(typ, path string, cache *Cache) {
ldb, err := leveldb.OpenFile(path, &opt.Options{
WriteBuffer: 4 * opt.KiB,
})
if err != nil {
log.Fatalf("failed to read cache config: %v", err)
log.Fatalf("open cache %s db failed: %v", typ, err)
}
cache.ldb = ldb
}
open := func(typ string, cache *Cache) {
file := conf[typ]
if file == "" {
file = fmt.Sprintf("data/%s.db", typ)
}
if global.PathExists(file) {
db, err := btree.Open(file)
if err != nil {
log.Fatalf("open %s cache failed: %v", typ, err)
}
cache.db = db
} else {
db, err := btree.Create(file)
if err != nil {
log.Fatalf("create %s cache failed: %v", typ, err)
}
cache.db = db
}
}
open("image", &Image)
open("video", &Video)
open("image", "data/images", &Image)
open("video", "data/videos", &Video)
}

View File

@ -79,11 +79,6 @@ database: # 数据库相关设置
# 关闭将无法使用 撤回 回复 get_msg 等上下文相关功能
enable: true
# 媒体文件缓存, 删除此项则使用缓存文件(旧版行为)
cache:
image: data/image.db
video: data/video.db
# 连接服务列表
servers:
# 添加方式,同一连接方式可添加多个,具体配置说明请查看文档