wp-go/cache/cache.go

47 lines
934 B
Go
Raw Normal View History

2022-09-19 09:39:00 +00:00
package cache
import (
"log"
"sync"
"time"
)
type SliceCache[T any] struct {
data []T
mutex *sync.Mutex
setCacheFunc func() ([]T, error)
expireTime time.Duration
setTime time.Time
}
func NewSliceCache[T any](fun func() ([]T, error), duration time.Duration) *SliceCache[T] {
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-19 09:39:00 +00:00
func (c *SliceCache[T]) GetCache() []T {
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-19 09:39:00 +00:00
r, err := c.setCacheFunc()
if err != nil {
log.Printf("set cache err[%s]", err)
return nil
}
2022-09-19 12:15:10 +00:00
c.mutex.Lock()
defer c.mutex.Unlock()
2022-09-19 09:39:00 +00:00
c.setTime = time.Now()
c.data = r
}
return c.data
}