完善缓存

This commit is contained in:
xing 2022-09-20 16:11:20 +08:00
parent c7b40f76b1
commit 927d2d6f9b
3 changed files with 106 additions and 18 deletions

View File

@ -172,7 +172,8 @@ func Archives() (r []models.PostArchive) {
} }
func Categories(ctx context.Context) []models.WpTermsMy { func Categories(ctx context.Context) []models.WpTermsMy {
return categoryCaches.GetCache(ctx, time.Second) r, _ := categoryCaches.GetCache(ctx, time.Second)
return r
} }
func categories(...any) (terms []models.WpTermsMy, err error) { func categories(...any) (terms []models.WpTermsMy, err error) {
@ -197,7 +198,8 @@ func categories(...any) (terms []models.WpTermsMy, err error) {
} }
func RecentPosts(ctx context.Context) (r []models.WpPosts) { func RecentPosts(ctx context.Context) (r []models.WpPosts) {
return recentPostsCaches.GetCache(ctx, time.Second) r, _ = recentPostsCaches.GetCache(ctx, time.Second)
return
} }
func recentPosts(...any) (r []models.WpPosts, err error) { func recentPosts(...any) (r []models.WpPosts, err error) {
r, err = models.Find[models.WpPosts](models.SqlBuilder{{ r, err = models.Find[models.WpPosts](models.SqlBuilder{{

75
cache/map.go vendored Normal file
View File

@ -0,0 +1,75 @@
package cache
import (
"context"
"errors"
"fmt"
"sync"
"time"
)
type MapCache[K comparable, V any] struct {
data map[K]V
mutex *sync.Mutex
setCacheFunc func(...any) (V, error)
expireTime time.Duration
setTime time.Time
incr int
}
func NewMapCache[K comparable, V any](fun func(...any) (V, error), duration time.Duration) *MapCache[K, V] {
return &MapCache[K, V]{
mutex: &sync.Mutex{},
setCacheFunc: fun,
expireTime: duration,
}
}
func (c *MapCache[K, V]) FlushCache(k any) {
c.mutex.Lock()
defer c.mutex.Unlock()
key := k.(K)
delete(c.data, key)
}
func (c *MapCache[K, V]) GetCache(ctx context.Context, key K, timeout time.Duration, params ...any) (V, error) {
l := len(c.data)
var err error
expired := time.Duration(c.setTime.Unix())+c.expireTime/time.Second < time.Duration(time.Now().Unix())
if l < 1 || (l > 0 && c.expireTime >= 0 && expired) {
t := c.incr
call := func() {
c.mutex.Lock()
defer c.mutex.Unlock()
if c.incr > t {
return
}
r, er := c.setCacheFunc(params...)
if err != nil {
err = er
return
}
c.setTime = time.Now()
c.data[key] = r
c.incr++
}
if timeout > 0 {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
done := make(chan struct{})
go func() {
call()
done <- struct{}{}
}()
select {
case <-ctx.Done():
err = errors.New(fmt.Sprintf("get cache %v %s", key, ctx.Err().Error()))
case <-done:
}
} else {
call()
}
}
return c.data[key], err
}

View File

@ -2,7 +2,8 @@ package cache
import ( import (
"context" "context"
"log" "errors"
"fmt"
"sync" "sync"
"time" "time"
) )
@ -30,36 +31,46 @@ func (c *SliceCache[T]) FlushCache() {
c.data = nil c.data = nil
} }
func (c *SliceCache[T]) GetCache(ctx context.Context, timeout time.Duration) []T { func (c *SliceCache[T]) GetCache(ctx context.Context, timeout time.Duration, params ...any) ([]T, error) {
l := len(c.data) l := len(c.data)
var err error
expired := time.Duration(c.setTime.Unix())+c.expireTime/time.Second < time.Duration(time.Now().Unix()) expired := time.Duration(c.setTime.Unix())+c.expireTime/time.Second < time.Duration(time.Now().Unix())
if l < 1 || (l > 0 && c.expireTime >= 0 && expired) { if l < 1 || (l > 0 && c.expireTime >= 0 && expired) {
t := c.incr t := c.incr
ctx, cancel := context.WithTimeout(ctx, timeout) call := func() {
defer cancel()
done := make(chan struct{})
go func() {
c.mutex.Lock() c.mutex.Lock()
defer c.mutex.Unlock() defer c.mutex.Unlock()
if c.incr > t { if c.incr > t {
return return
} }
r, err := c.setCacheFunc() r, er := c.setCacheFunc(params...)
if err != nil { if err != nil {
log.Printf("set cache err[%s]", err) err = er
return return
} }
c.setTime = time.Now() c.setTime = time.Now()
c.data = r c.data = r
c.incr++ c.incr++
done <- struct{}{}
}()
select {
case <-ctx.Done():
log.Printf("get cache timeout")
case <-done:
} }
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:
}
} else {
call()
}
} }
return c.data return c.data, err
} }