This commit is contained in:
xing 2022-10-14 21:42:24 +08:00
parent a6049ff78a
commit 952ccfd2ca
2 changed files with 12 additions and 11 deletions

9
cache/map.go vendored
View File

@ -141,18 +141,19 @@ func (m *MapCache[K, V]) GetCache(c context.Context, key K, timeout time.Duratio
call := func() { call := func() {
m.mutex.Lock() m.mutex.Lock()
defer m.mutex.Unlock() defer m.mutex.Unlock()
if data.incr > t { da, ok := m.data.Load(key)
if ok && da.incr > t {
return return
} else {
da = data
} }
r, er := m.cacheFunc(params...) r, er := m.cacheFunc(params...)
if err != nil { if err != nil {
err = er err = er
return return
} }
data.setTime = time.Now() m.set(key, r)
data.data = r data.data = r
m.data.Store(key, data)
data.incr++
} }
if timeout > 0 { if timeout > 0 {
ctx, cancel := context.WithTimeout(c, timeout) ctx, cancel := context.WithTimeout(c, timeout)

14
cache/slice.go vendored
View File

@ -53,22 +53,22 @@ func (c *SliceCache[T]) GetCache(ctx context.Context, timeout time.Duration, par
if l < 1 || (l > 0 && v.expireTime >= 0 && expired) { if l < 1 || (l > 0 && v.expireTime >= 0 && expired) {
t := v.incr t := v.incr
call := func() { call := func() {
v := c.v.Load()
v.mutex.Lock() v.mutex.Lock()
defer v.mutex.Unlock() defer v.mutex.Unlock()
if v.incr > t { vv := c.v.Load()
if vv.incr > t {
return return
} }
r, er := v.setCacheFunc(params...) r, er := vv.setCacheFunc(params...)
if err != nil { if err != nil {
err = er err = er
return return
} }
v.setTime = time.Now() vv.setTime = time.Now()
v.data = r vv.data = r
data = r data = r
v.incr++ vv.incr++
c.v.Store(v) c.v.Store(vv)
} }
if timeout > 0 { if timeout > 0 {
ctx, cancel := context.WithTimeout(ctx, timeout) ctx, cancel := context.WithTimeout(ctx, timeout)