1 Star 0 Fork 0

地瓜2015 / go-utils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
memory.go 1.77 KB
一键复制 编辑 原始数据 按行查看 历史
zkdfbb 提交于 2021-02-07 09:01 . add storage
package utils
import (
"sync"
"sync/atomic"
"time"
)
// Storage define
type Storage struct {
sync.RWMutex
data map[string]item // data
ts uint64 // timestamp
}
type item struct {
v interface{} // val
e uint64 // exp
}
// NewStorage return new storage
func NewStorage() *Storage {
store := &Storage{
data: make(map[string]item),
ts: uint64(time.Now().Unix()),
}
go store.gc(10 * time.Millisecond)
go store.updater(1 * time.Second)
return store
}
// Get value by key
func (s *Storage) Get(key string) interface{} {
s.RLock()
v, ok := s.data[key]
s.RUnlock()
if !ok || v.e != 0 && v.e <= atomic.LoadUint64(&s.ts) {
return nil
}
return v.v
}
// Set key with value
func (s *Storage) Set(key string, val interface{}, ttl time.Duration) {
var exp uint64
if ttl > 0 {
exp = uint64(ttl.Seconds()) + atomic.LoadUint64(&s.ts)
}
s.Lock()
s.data[key] = item{val, exp}
s.Unlock()
}
// TTL return ttl
func (s *Storage) TTL(key string) uint64 {
s.RLock()
v, ok := s.data[key]
s.RUnlock()
if !ok || v.e == 0 {
return 0
}
return v.e - atomic.LoadUint64(&s.ts)
}
// Delete key by key
func (s *Storage) Delete(key string) {
s.Lock()
delete(s.data, key)
s.Unlock()
}
// Reset all keys
func (s *Storage) Reset() {
s.Lock()
s.data = make(map[string]item)
s.Unlock()
}
func (s *Storage) updater(sleep time.Duration) {
for {
time.Sleep(sleep)
atomic.StoreUint64(&s.ts, uint64(time.Now().Unix()))
}
}
func (s *Storage) gc(sleep time.Duration) {
expired := []string{}
for {
time.Sleep(sleep)
expired = expired[:0]
s.RLock()
for key, v := range s.data {
if v.e != 0 && v.e <= atomic.LoadUint64(&s.ts) {
expired = append(expired, key)
}
}
s.RUnlock()
s.Lock()
for i := range expired {
delete(s.data, expired[i])
}
s.Unlock()
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/zkdfbb/go-utils.git
git@gitee.com:zkdfbb/go-utils.git
zkdfbb
go-utils
go-utils
v0.1.7

搜索帮助

344bd9b3 5694891 D2dac590 5694891