完善缓存机制

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

View File

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

View File

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

41
cache/cache.go vendored
View File

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