wp-go/cache/cache.go

66 lines
1.3 KiB
Go
Raw Normal View History

2022-09-19 09:39:00 +00:00
package cache
import (
2022-09-20 04:00:09 +00:00
"context"
2022-09-19 09:39:00 +00:00
"log"
"sync"
"time"
)
type SliceCache[T any] struct {
data []T
mutex *sync.Mutex
2022-09-20 04:00:09 +00:00
setCacheFunc func(...any) ([]T, error)
2022-09-19 09:39:00 +00:00
expireTime time.Duration
setTime time.Time
2022-09-20 04:00:09 +00:00
incr int
2022-09-19 09:39:00 +00:00
}
2022-09-20 04:00:09 +00:00
func NewSliceCache[T any](fun func(...any) ([]T, error), duration time.Duration) *SliceCache[T] {
2022-09-19 09:39:00 +00:00
return &SliceCache[T]{
mutex: &sync.Mutex{},
setCacheFunc: fun,
expireTime: duration,
}
}
2022-09-19 14:02:34 +00:00
func (c *SliceCache[T]) FlushCache() {
c.mutex.Lock()
defer c.mutex.Unlock()
c.data = nil
}
2022-09-20 04:00:09 +00:00
func (c *SliceCache[T]) GetCache(ctx context.Context, timeout time.Duration) []T {
2022-09-19 09:39:00 +00:00
l := len(c.data)
expired := time.Duration(c.setTime.Unix())+c.expireTime/time.Second < time.Duration(time.Now().Unix())
2022-09-19 14:20:10 +00:00
if l < 1 || (l > 0 && c.expireTime >= 0 && expired) {
2022-09-20 04:00:09 +00:00
t := c.incr
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
done := make(chan struct{})
go func() {
c.mutex.Lock()
defer c.mutex.Unlock()
if c.incr > t {
return
}
r, err := c.setCacheFunc()
if err != nil {
log.Printf("set cache err[%s]", err)
return
}
c.setTime = time.Now()
c.data = r
c.incr++
done <- struct{}{}
}()
select {
case <-ctx.Done():
log.Printf("get cache timeout")
case <-done:
2022-09-19 09:39:00 +00:00
}
}
return c.data
}