wp-go/cache/slice.go

83 lines
1.5 KiB
Go
Raw Permalink 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-20 08:11:20 +00:00
"errors"
"fmt"
2022-09-19 09:39:00 +00:00
"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-10-07 12:37:42 +00:00
func (c *SliceCache[T]) SetTime() time.Time {
return c.setTime
}
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 08:11:20 +00:00
func (c *SliceCache[T]) GetCache(ctx context.Context, timeout time.Duration, params ...any) ([]T, error) {
2022-09-19 09:39:00 +00:00
l := len(c.data)
2022-09-20 08:55:13 +00:00
data := c.data
2022-09-20 08:11:20 +00:00
var err error
2022-09-28 12:02:43 +00:00
expired := time.Duration(c.setTime.UnixNano())+c.expireTime < time.Duration(time.Now().UnixNano())
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
2022-09-20 08:11:20 +00:00
call := func() {
2022-09-20 04:00:09 +00:00
c.mutex.Lock()
defer c.mutex.Unlock()
if c.incr > t {
return
}
2022-09-20 08:11:20 +00:00
r, er := c.setCacheFunc(params...)
2022-09-20 04:00:09 +00:00
if err != nil {
2022-09-20 08:11:20 +00:00
err = er
2022-09-20 04:00:09 +00:00
return
}
c.setTime = time.Now()
c.data = r
2022-09-20 08:55:13 +00:00
data = r
2022-09-20 04:00:09 +00:00
c.incr++
2022-09-20 08:11:20 +00:00
}
if timeout > 0 {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
done := make(chan struct{})
go func() {
call()
done <- struct{}{}
close(done)
}()
select {
case <-ctx.Done():
err = errors.New(fmt.Sprintf("get cache %s", ctx.Err().Error()))
case <-done:
2022-09-20 04:00:09 +00:00
2022-09-20 08:11:20 +00:00
}
} else {
call()
2022-09-19 09:39:00 +00:00
}
2022-09-20 08:11:20 +00:00
2022-09-19 09:39:00 +00:00
}
2022-09-20 08:55:13 +00:00
return data, err
2022-09-19 09:39:00 +00:00
}