代码优化

This commit is contained in:
xing 2022-09-19 20:15:10 +08:00
parent f85cace016
commit 972ca5625f
4 changed files with 54 additions and 29 deletions

View File

@ -5,6 +5,7 @@ import (
"github/fthvgb1/wp-go/cache"
"github/fthvgb1/wp-go/models"
"github/fthvgb1/wp-go/vars"
"log"
"strings"
"sync"
"time"
@ -13,16 +14,44 @@ import (
var PostsCache sync.Map
var PostContextCache sync.Map
var archivesCaches *cache.SliceCache[models.PostArchive]
var archivesCaches *Arch[models.PostArchive]
var categoryCaches *cache.SliceCache[models.WpTermsMy]
var recentPostsCaches *cache.SliceCache[models.WpPosts]
func InitCache() {
archivesCaches = cache.NewSliceCache[models.PostArchive](archives, vars.Conf.ArchiveCacheTime)
archivesCaches = &Arch[models.PostArchive]{
mutex: &sync.Mutex{},
setCacheFunc: archives,
}
categoryCaches = cache.NewSliceCache[models.WpTermsMy](categories, vars.Conf.CategoryCacheTime)
recentPostsCaches = cache.NewSliceCache[models.WpPosts](recentPosts, vars.Conf.RecentPostCacheTime)
}
type Arch[T any] struct {
cache.SliceCache[T]
data []T
mutex *sync.Mutex
setCacheFunc func() ([]T, error)
month time.Month
}
func (c *Arch[T]) GetCache() []T {
l := len(c.data)
m := time.Now().Month()
if l > 0 && c.month != m || l < 1 {
r, err := c.setCacheFunc()
if err != nil {
log.Printf("set cache err[%s]", err)
return nil
}
c.mutex.Lock()
defer c.mutex.Unlock()
c.month = m
c.data = r
}
return c.data
}
type PostContext struct {
Prev models.WpPosts
Next models.WpPosts
@ -55,7 +84,7 @@ func getPostContext(t time.Time) (prev, next models.WpPosts, err error) {
{"post_date", ">", t.Format("2006-01-02 15:04:05")},
{"post_status", "publish"},
{"post_type", "post"},
}, "ID,post_title,post_password")
}, "ID,post_title,post_password", nil)
if _, ok := PostsCache.Load(next.Id); !ok {
}
@ -63,7 +92,7 @@ func getPostContext(t time.Time) (prev, next models.WpPosts, err error) {
{"post_date", "<", t.Format("2006-01-02 15:04:05")},
{"post_status", "publish"},
{"post_type", "post"},
}, "ID,post_title")
}, "ID,post_title", models.SqlBuilder{{"post_date", "desc"}})
return
}

View File

@ -148,7 +148,18 @@ func (h *indexHandle) getTotalPage(totalRaws int) int {
func Index(c *gin.Context) {
h := newIndexHandle(c)
h.parseParams()
ginH := gin.H{}
archive := common.Archives()
recent := common.RecentPosts()
categoryItems := common.Categories()
ginH := gin.H{
"options": models.Options,
"recentPosts": recent,
"archives": archive,
"categories": categoryItems,
"search": h.search,
"header": h.header,
"title": h.getTitle(),
}
postIds, totalRaw, err := models.SimplePagination[models.WpPosts](h.where, "ID", "", h.page, h.pageSize, h.orderBy, h.join, h.postType, h.status)
defer func() {
c.HTML(http.StatusOK, "posts/index.gohtml", ginH)
@ -174,27 +185,16 @@ func Index(c *gin.Context) {
}
postIds[i] = px
}
recent := common.RecentPosts()
for i, post := range recent {
if post.PostPassword != "" && pw != post.PostPassword {
common.PasswdProjectContent(&recent[i])
}
}
archive := common.Archives()
categoryItems := common.Categories()
q := c.Request.URL.Query().Encode()
ginH = gin.H{
"posts": postIds,
"options": models.Options,
"recentPosts": recent,
"archives": archive,
"categories": categoryItems,
"totalPage": h.getTotalPage(totalRaw),
"pagination": pagination(h.page, h.totalPage, h.paginationStep, c.Request.URL.Path, q),
"search": h.search,
"header": h.header,
"title": h.getTitle(),
}
ginH["posts"] = postIds
ginH["totalPage"] = h.getTotalPage(totalRaw)
ginH["pagination"] = pagination(h.page, h.totalPage, h.paginationStep, c.Request.URL.Path, q)
ginH["title"] = h.getTitle()
}
func pagination(currentPage, totalPage, step int, path, query string) (html string) {

8
cache/cache.go vendored
View File

@ -22,12 +22,6 @@ func NewSliceCache[T any](fun func() ([]T, error), duration time.Duration) *Slic
}
}
func (c *SliceCache[T]) FlushCache() {
c.mutex.Lock()
defer c.mutex.Unlock()
c.data = nil
}
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())
@ -37,6 +31,8 @@ func (c *SliceCache[T]) GetCache() []T {
log.Printf("set cache err[%s]", err)
return nil
}
c.mutex.Lock()
defer c.mutex.Unlock()
c.setTime = time.Now()
c.data = r
}

View File

@ -221,11 +221,11 @@ func FindOneById[T Model](id int) (T, error) {
return r, nil
}
func FirstOne[T Model](where ParseWhere, fields string, in ...[]interface{}) (T, error) {
func FirstOne[T Model](where ParseWhere, fields string, order SqlBuilder, in ...[]interface{}) (T, error) {
var r T
w, args := where.ParseWhere(in...)
tp := "select %s from %s %s"
sql := fmt.Sprintf(tp, fields, r.Table(), w)
tp := "select %s from %s %s %s"
sql := fmt.Sprintf(tp, fields, r.Table(), w, order.parseOrderBy())
err := db.Db.Get(&r, sql, args...)
if err != nil {
return r, err