get添加错误码
This commit is contained in:
@@ -1,6 +1,7 @@
|
|||||||
package cachex
|
package cachex
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -10,11 +11,12 @@ import (
|
|||||||
// 1.全局单实例
|
// 1.全局单实例
|
||||||
// 到设定的点就删除
|
// 到设定的点就删除
|
||||||
|
|
||||||
type cache struct{
|
type cache struct {
|
||||||
store sync.Map
|
store sync.Map
|
||||||
}
|
}
|
||||||
|
|
||||||
var one sync.Once
|
var one sync.Once
|
||||||
var c cache
|
var c *cache
|
||||||
|
|
||||||
type cacheData struct {
|
type cacheData struct {
|
||||||
key string
|
key string
|
||||||
@@ -22,11 +24,13 @@ type cacheData struct {
|
|||||||
expire time.Time
|
expire time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var ErrorEmpty error = errors.New("empty cache")
|
||||||
|
|
||||||
func NewCache() *cache {
|
func NewCache() *cache {
|
||||||
one.Do(func() {
|
one.Do(func() {
|
||||||
c = cache{}
|
c = &cache{}
|
||||||
|
|
||||||
go func(){
|
go func() {
|
||||||
for {
|
for {
|
||||||
c.store.Range(func(key, value interface{}) bool {
|
c.store.Range(func(key, value interface{}) bool {
|
||||||
if value.(*cacheData).expire.Before(time.Now()) {
|
if value.(*cacheData).expire.Before(time.Now()) {
|
||||||
@@ -39,27 +43,30 @@ func NewCache() *cache {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
})
|
})
|
||||||
return &c
|
return c
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置缓存
|
// 设置缓存
|
||||||
func (c *cache) Set(key string, value interface{}, expire time.Duration) {
|
func (c *cache) Set(key string, value interface{}, expire time.Duration) {
|
||||||
|
if expire == 0 {
|
||||||
|
expire = time.Hour * 24 * 365
|
||||||
|
}
|
||||||
cd := &cacheData{key, value, time.Now().Add(expire)}
|
cd := &cacheData{key, value, time.Now().Add(expire)}
|
||||||
c.store.Store(key, cd)
|
c.store.Store(key, cd)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 读取缓存
|
// 读取缓存
|
||||||
func (c *cache) Get(key string) interface{} {
|
func (c *cache) Get(key string) (interface{}, error) {
|
||||||
if v, ok := c.store.Load(key); ok {
|
if v, ok := c.store.Load(key); ok {
|
||||||
|
|
||||||
cc := v.(*cacheData)
|
cc := v.(*cacheData)
|
||||||
if cc.expire.Before(time.Now()) {
|
if cc.expire.Before(time.Now()) {
|
||||||
c.store.Delete(key)
|
c.store.Delete(key)
|
||||||
return nil
|
return nil, ErrorEmpty
|
||||||
}
|
}
|
||||||
return cc.data
|
return cc.data, nil
|
||||||
}
|
}
|
||||||
return nil
|
return nil, ErrorEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
// 删除缓存
|
// 删除缓存
|
||||||
|
|||||||
Reference in New Issue
Block a user