1 Star 1 Fork 0

凡卡 / libp2parea

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
cache.go 1.81 KB
一键复制 编辑 原始数据 按行查看 历史
凡卡 提交于 2023-11-29 11:01 . first commit
package cachedata
import (
"gitee.com/prestonTao/utils"
"sync"
"time"
)
//存储结构
type Cache struct {
Data *sync.Map //存储共享数据(key/value:hash/cachedata)
Time time.Time //更新时间
}
func NewCache() *Cache {
c := new(Cache)
c.Data = new(sync.Map)
c.Time = time.Now()
return c
}
//格式化保存key,value
//uptime true 则更新时间
func (c *Cache) Save(d *CacheData) {
k, v := d.buildKV()
c.Data.Store(k, v)
}
//根据KEY获取原始数据DATA
func (c *Cache) Get(key []byte) []byte {
khash := buildHash(key)
k := utils.Bytes2string(khash) // khash.B58String()
data, ok := c.Data.Load(k)
if ok {
b := data.([]byte)
cd, err := Parse(b)
if err != nil {
return nil
}
return cd.Value
}
return nil
}
//根据KEY删除数据
func (c *Cache) Del(key []byte) {
khash := buildHash(key)
k := utils.Bytes2string(khash) // khash.B58String()
c.Data.Delete(k)
}
//根据hash id 获取原始数据DATA
func (c *Cache) GetByHash(id *utils.Multihash) []byte {
k := utils.Bytes2string(id) //id.B58String()
data, ok := c.Data.Load(k)
if ok {
b := data.([]byte)
cd, err := Parse(b)
if err != nil {
return nil
}
return cd.Value
}
return nil
}
//根据原始key获取cachedata
func (c *Cache) GetCacheData(key []byte) *CacheData {
khash := buildHash(key)
k := utils.Bytes2string(khash) //khash.B58String()
data, ok := c.Data.Load(k)
if ok {
b := data.([]byte)
cd, err := Parse(b)
if err != nil {
return nil
}
return cd
}
return nil
}
//根据hash id 获取cachedata
func (c *Cache) GetCacheDataByHash(id *utils.Multihash) *CacheData {
k := utils.Bytes2string(id) //id.B58String()
data, ok := c.Data.Load(k)
if ok {
b := data.([]byte)
cd, err := Parse(b)
if err != nil {
return nil
}
return cd
}
return nil
}
func (c *Cache) UpTime() {
c.Time = time.Now()
}
Go
1
https://gitee.com/prestonTao/libp2parea.git
git@gitee.com:prestonTao/libp2parea.git
prestonTao
libp2parea
libp2parea
58a2b3547940

搜索帮助