去掉前缀的输入

This commit is contained in:
yun
2024-04-12 16:44:21 +08:00
parent a54973797d
commit 35c671f1e1
2 changed files with 5 additions and 14 deletions
+4 -13
View File
@@ -12,8 +12,7 @@ import (
// 到设定的点就删除 // 到设定的点就删除
type cache struct { type cache struct {
prefix string store sync.Map
store sync.Map
} }
type cacheData struct { type cacheData struct {
@@ -24,11 +23,9 @@ type cacheData struct {
var ErrorEmpty error = errors.New("empty cache") var ErrorEmpty error = errors.New("empty cache")
func NewCache(prefix string) *cache { func NewCache() *cache {
c := &cache{ c := &cache{}
prefix: prefix,
}
go func() { go func() {
for { for {
@@ -51,13 +48,11 @@ func (c *cache) Set(key string, value interface{}, expire time.Duration) {
expire = time.Hour * 24 * 365 expire = time.Hour * 24 * 365
} }
cd := &cacheData{key, value, time.Now().Add(expire)} cd := &cacheData{key, value, time.Now().Add(expire)}
key = c.prefix + key
c.store.Store(key, cd) c.store.Store(key, cd)
} }
// 读取缓存 // 读取缓存
func (c *cache) Get(key string) (interface{}, error) { func (c *cache) Get(key string) (interface{}, error) {
key = c.prefix + key
if v, ok := c.store.Load(key); ok { if v, ok := c.store.Load(key); ok {
cc := v.(*cacheData) cc := v.(*cacheData)
@@ -72,17 +67,13 @@ func (c *cache) Get(key string) (interface{}, error) {
// 删除缓存 // 删除缓存
func (c *cache) Delete(key string) { func (c *cache) Delete(key string) {
key = c.prefix + key
c.store.Delete(key) c.store.Delete(key)
} }
// 清空缓存 // 清空缓存
func (c *cache) Clear() { func (c *cache) Clear() {
c.store.Range(func(key, value interface{}) bool { c.store.Range(func(key, value interface{}) bool {
// 根据前缀删除 c.store.Delete(key)
if key.(string)[:len(c.prefix)] == c.prefix {
c.store.Delete(key)
}
return true return true
}) })
} }
+1 -1
View File
@@ -9,7 +9,7 @@ import (
) )
func TestCache(t *testing.T) { func TestCache(t *testing.T) {
c := cachex.NewCache("") c := cachex.NewCache()
c.Set("test", "test", time.Second*5) c.Set("test", "test", time.Second*5)