代码拉取完成,页面将自动刷新
package cache
import (
"sync"
"gitee.com/haodreams/golib/logs"
"gitee.com/haodreams/golib/lz4file"
"github.com/ugorji/go/codec"
)
// Cache 缓存数据
type Cache struct {
kv map[string]string
lock sync.RWMutex
}
// New 新建一个缓存
func New() *Cache {
c := new(Cache)
c.Init()
return c
}
// Init 初始化
func (m *Cache) Init() {
m.kv = map[string]string{}
}
// Save 保存
func (m *Cache) Save(path string) {
m.lock.RLock()
defer m.lock.RUnlock()
mh := new(codec.MsgpackHandle)
var data []byte
if len(m.kv) > 0 {
err := codec.NewEncoderBytes(&data, mh).Encode(&m.kv)
if err != nil {
logs.Warn("Encode msgpack", err.Error())
return
}
err = lz4file.SaveLz4File(path, data)
if err != nil {
logs.Warn("保存Msgpack文件错误", err.Error())
return
}
}
}
// Load 加载缓存
func (m *Cache) Load(path string) (err error) {
m.lock.Lock()
defer m.lock.Unlock()
mh := new(codec.MsgpackHandle)
//加载风机的中间变量
data, err := lz4file.LoadLz4File(path)
if err != nil {
logs.Error("加载 缓存数据错误", err.Error())
return
}
err = codec.NewDecoderBytes(data, mh).Decode(&m.kv)
if err != nil {
logs.Error("lz4 解码失败", err.Error())
return
}
return err
}
// Set 设置值
// force 是否强制设置值
func (m *Cache) Set(key, value string, force ...bool) {
m.lock.Lock()
defer m.lock.Unlock()
if len(force) > 0 && force[0] {
m.kv[key] = value
return
}
if _, ok := m.kv[key]; ok {
return
}
m.kv[key] = value
}
// Get 获取值
func (m *Cache) Get(key string) (value string, ok bool) {
m.lock.RLock()
defer m.lock.RUnlock()
value, ok = m.kv[key]
return
}
// Each 遍历每一个元素
func (m *Cache) Each(f func(key, value string) error) (err error) {
m.lock.RLock()
defer m.lock.RUnlock()
for key, value := range m.kv {
err = f(key, value)
if err != nil {
return
}
}
return
}
// Clear 清空
func (m *Cache) Clear() {
m.lock.Lock()
defer m.lock.Unlock()
m.kv = map[string]string{}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。