完善缓存机制

This commit is contained in:
xing 2022-09-20 12:00:09 +08:00
parent 999e623b82
commit c7b40f76b1
4 changed files with 45 additions and 21 deletions

View File

@ -1,6 +1,7 @@
package common
import (
"context"
"fmt"
"github/fthvgb1/wp-go/cache"
"github/fthvgb1/wp-go/models"
@ -170,11 +171,11 @@ func Archives() (r []models.PostArchive) {
return archivesCaches.GetCache()
}
func Categories() []models.WpTermsMy {
return categoryCaches.GetCache()
func Categories(ctx context.Context) []models.WpTermsMy {
return categoryCaches.GetCache(ctx, time.Second)
}
func categories() (terms []models.WpTermsMy, err error) {
func categories(...any) (terms []models.WpTermsMy, err error) {
var in = []interface{}{"category"}
terms, err = models.Find[models.WpTermsMy](models.SqlBuilder{
{"tt.count", ">", "0", "int"},
@ -195,10 +196,10 @@ func categories() (terms []models.WpTermsMy, err error) {
return
}
func RecentPosts() (r []models.WpPosts) {
return recentPostsCaches.GetCache()
func RecentPosts(ctx context.Context) (r []models.WpPosts) {
return recentPostsCaches.GetCache(ctx, time.Second)
}
func recentPosts() (r []models.WpPosts, err error) {
func recentPosts(...any) (r []models.WpPosts, err error) {
r, err = models.Find[models.WpPosts](models.SqlBuilder{{
"post_type", "post",
}, {"post_status", "publish"}}, "ID,post_title,post_password", "", models.SqlBuilder{{"post_date", "desc"}}, nil, 5)

View File

@ -1,6 +1,7 @@
package actions
import (
"context"
"fmt"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
@ -12,9 +13,10 @@ import (
func Detail(c *gin.Context) {
var err error
recent := common.RecentPosts()
ctx := context.TODO()
recent := common.RecentPosts(ctx)
archive := common.Archives()
categoryItems := common.Categories()
categoryItems := common.Categories(ctx)
var h = gin.H{
"title": models.Options["blogname"],
"options": models.Options,

View File

@ -1,6 +1,7 @@
package actions
import (
"context"
"fmt"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
@ -148,9 +149,10 @@ func (h *indexHandle) getTotalPage(totalRaws int) int {
func Index(c *gin.Context) {
h := newIndexHandle(c)
h.parseParams()
ctx := context.TODO()
archive := common.Archives()
recent := common.RecentPosts()
categoryItems := common.Categories()
recent := common.RecentPosts(ctx)
categoryItems := common.Categories(ctx)
ginH := gin.H{
"options": models.Options,
"recentPosts": recent,

41
cache/cache.go vendored
View File

@ -1,6 +1,7 @@
package cache
import (
"context"
"log"
"sync"
"time"
@ -9,12 +10,13 @@ import (
type SliceCache[T any] struct {
data []T
mutex *sync.Mutex
setCacheFunc func() ([]T, error)
setCacheFunc func(...any) ([]T, error)
expireTime time.Duration
setTime time.Time
incr int
}
func NewSliceCache[T any](fun func() ([]T, error), duration time.Duration) *SliceCache[T] {
func NewSliceCache[T any](fun func(...any) ([]T, error), duration time.Duration) *SliceCache[T] {
return &SliceCache[T]{
mutex: &sync.Mutex{},
setCacheFunc: fun,
@ -28,19 +30,36 @@ func (c *SliceCache[T]) FlushCache() {
c.data = nil
}
func (c *SliceCache[T]) GetCache() []T {
func (c *SliceCache[T]) GetCache(ctx context.Context, timeout time.Duration) []T {
l := len(c.data)
expired := time.Duration(c.setTime.Unix())+c.expireTime/time.Second < time.Duration(time.Now().Unix())
if l < 1 || (l > 0 && c.expireTime >= 0 && expired) {
r, err := c.setCacheFunc()
if err != nil {
log.Printf("set cache err[%s]", err)
return nil
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:
}
c.mutex.Lock()
defer c.mutex.Unlock()
c.setTime = time.Now()
c.data = r
}
return c.data
}