From 952ccfd2cae1e396806829c7ada4671d41c06fd8 Mon Sep 17 00:00:00 2001 From: xing Date: Fri, 14 Oct 2022 21:42:24 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cache/map.go | 9 +++++---- cache/slice.go | 14 +++++++------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/cache/map.go b/cache/map.go index 534867d..7cbad98 100644 --- a/cache/map.go +++ b/cache/map.go @@ -141,18 +141,19 @@ func (m *MapCache[K, V]) GetCache(c context.Context, key K, timeout time.Duratio call := func() { m.mutex.Lock() defer m.mutex.Unlock() - if data.incr > t { + da, ok := m.data.Load(key) + if ok && da.incr > t { return + } else { + da = data } r, er := m.cacheFunc(params...) if err != nil { err = er return } - data.setTime = time.Now() + m.set(key, r) data.data = r - m.data.Store(key, data) - data.incr++ } if timeout > 0 { ctx, cancel := context.WithTimeout(c, timeout) diff --git a/cache/slice.go b/cache/slice.go index 4f6ea02..8e9d163 100644 --- a/cache/slice.go +++ b/cache/slice.go @@ -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) { t := v.incr call := func() { - v := c.v.Load() v.mutex.Lock() defer v.mutex.Unlock() - if v.incr > t { + vv := c.v.Load() + if vv.incr > t { return } - r, er := v.setCacheFunc(params...) + r, er := vv.setCacheFunc(params...) if err != nil { err = er return } - v.setTime = time.Now() - v.data = r + vv.setTime = time.Now() + vv.data = r data = r - v.incr++ - c.v.Store(v) + vv.incr++ + c.v.Store(vv) } if timeout > 0 { ctx, cancel := context.WithTimeout(ctx, timeout)