缓存设置

This commit is contained in:
xing 2022-09-19 17:39:00 +08:00
parent dd4560d4f8
commit 0dfeaa5a7b
4 changed files with 198 additions and 134 deletions

View File

@ -2,13 +2,19 @@ package common
import ( import (
"fmt" "fmt"
"github/fthvgb1/wp-go/cache"
"github/fthvgb1/wp-go/models" "github/fthvgb1/wp-go/models"
"strings" "strings"
"sync" "sync"
"time"
) )
var PostsCache sync.Map var PostsCache sync.Map
var archivesCaches = cache.NewSliceCache[models.PostArchive](archives, time.Hour*24)
var categoryCaches = cache.NewSliceCache[models.WpTermsMy](categories, time.Minute*30)
var recentPostsCaches = cache.NewSliceCache[models.WpPosts](recentPosts, time.Minute*30)
func GetPostFromCache(Id uint64) (r models.WpPosts) { func GetPostFromCache(Id uint64) (r models.WpPosts) {
p, ok := PostsCache.Load(Id) p, ok := PostsCache.Load(Id)
if ok { if ok {
@ -74,14 +80,21 @@ func QueryAndSetPostCache(postIds []models.WpPosts) (err error) {
return return
} }
func Archives() (r []models.PostArchive, err error) { func archives() ([]models.PostArchive, error) {
r, err = models.Find[models.PostArchive](models.SqlBuilder{ return models.Find[models.PostArchive](models.SqlBuilder{
{"post_type", "post"}, {"post_status", "publish"}, {"post_type", "post"}, {"post_status", "publish"},
}, "YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts", "year,month", models.SqlBuilder{{"year", "desc"}, {"month", "desc"}}, nil, 0) }, "YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts", "year,month", models.SqlBuilder{{"year", "desc"}, {"month", "desc"}}, nil, 0)
return
} }
func Categories() (terms []models.WpTermsMy, err error) { func Archives() (r []models.PostArchive) {
return archivesCaches.GetCache()
}
func Categories() []models.WpTermsMy {
return categoryCaches.GetCache()
}
func categories() (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"},
@ -102,7 +115,10 @@ func Categories() (terms []models.WpTermsMy, err error) {
return return
} }
func RecentPosts() (r []models.WpPosts, err error) { func RecentPosts() (r []models.WpPosts) {
return recentPostsCaches.GetCache()
}
func recentPosts() (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

@ -174,14 +174,14 @@ func Index(c *gin.Context) {
} }
postIds[i] = px postIds[i] = px
} }
recent, err := common.RecentPosts() recent := common.RecentPosts()
for i, post := range recent { for i, post := range recent {
if post.PostPassword != "" && pw != post.PostPassword { if post.PostPassword != "" && pw != post.PostPassword {
common.PasswdProjectContent(&recent[i]) common.PasswdProjectContent(&recent[i])
} }
} }
archive, err := common.Archives() archive := common.Archives()
categoryItems, err := common.Categories() categoryItems := common.Categories()
q := c.Request.URL.Query().Encode() q := c.Request.URL.Query().Encode()
ginH = gin.H{ ginH = gin.H{
"posts": postIds, "posts": postIds,

44
cache/cache.go vendored Normal file
View File

@ -0,0 +1,44 @@
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,
}
}
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())
if l > 0 && expired || l < 1 {
r, err := c.setCacheFunc()
if err != nil {
log.Printf("set cache err[%s]", err)
return nil
}
c.setTime = time.Now()
c.data = r
}
return c.data
}

View File

@ -1,18 +1,19 @@
{{template "layout/base" .}} {{template "layout/base" .}}
{{define "content"}} {{define "content"}}
<div id="primary" class="content-area"> {{ if .post.PostContent}}
<main id="main" class="site-main"> <div id="primary" class="content-area">
<article id="post-{{.post.Id}}" <main id="main" class="site-main">
class="post-{{.post.Id}} post type-post status-publish format-standard hentry category-uncategorized"> <article id="post-{{.post.Id}}"
class="post-{{.post.Id}} post type-post status-publish format-standard hentry category-uncategorized">
<header class="entry-header"> <header class="entry-header">
<h1 class="entry-title">{{.post.PostTitle}}</h1></header><!-- .entry-header --> <h1 class="entry-title">{{.post.PostTitle}}</h1></header><!-- .entry-header -->
<div class="entry-content"> <div class="entry-content">
{{.post.PostContent|unescaped}} {{.post.PostContent|unescaped}}
</div><!-- .entry-content --> </div><!-- .entry-content -->
<footer class="entry-footer"> <footer class="entry-footer">
<span class="posted-on"> <span class="posted-on">
<span class="screen-reader-text">发布于 </span> <span class="screen-reader-text">发布于 </span>
<a href="/p/{{.post.Id}}" rel="bookmark"> <a href="/p/{{.post.Id}}" rel="bookmark">
@ -21,132 +22,135 @@
</time> </time>
</a> </a>
</span> </span>
{{if .post.CategoriesHtml}} {{if .post.CategoriesHtml}}
<span class="cat-links"> <span class="cat-links">
<span class="screen-reader-text">分类 </span> <span class="screen-reader-text">分类 </span>
{{.post.CategoriesHtml|unescaped}} {{.post.CategoriesHtml|unescaped}}
</span> </span>
{{end}} {{end}}
{{if .post.TagsHtml}} {{if .post.TagsHtml}}
<span class="tags-links"> <span class="tags-links">
<span class="screen-reader-text">标签 </span> <span class="screen-reader-text">标签 </span>
{{.post.TagsHtml|unescaped}} {{.post.TagsHtml|unescaped}}
</span> </span>
{{end}}
</footer>
<!-- .entry-footer -->
</article><!-- #post-1 -->
<div id="comments" class="comments-area">
<h2 class="comments-title">
《{{.post.PostTitle}}》上有1条评论 </h2>
<ol class="comment-list">
<li id="comment-1" class="comment even thread-even depth-1">
<article id="div-comment-1" class="comment-body">
<footer class="comment-meta">
<div class="comment-author vcard">
<img alt=""
src="http://1.gravatar.com/avatar/d7a973c7dab26985da5f961be7b74480?s=56&amp;d=mm&amp;r=g"
srcset="http://1.gravatar.com/avatar/d7a973c7dab26985da5f961be7b74480?s=112&amp;d=mm&amp;r=g 2x"
class="avatar avatar-56 photo" height="56" width="56" loading="lazy">
<b class="fn">
<a href="https://cn.wordpress.org/" rel="external nofollow ugc"
class="url">一位WordPress评论者</a>
</b>
<span class="says">说道:</span></div><!-- .comment-author -->
<div class="comment-metadata">
<a href="/p/1#comment-1">
<time datetime="2022-08-19T09:26:37+08:00">2022年 8月 19日 上午9:26</time>
</a></div><!-- .comment-metadata -->
</footer><!-- .comment-meta -->
<div class="comment-content">
<p>您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 <a
href="https://cn.gravatar.com/">Gravatar</a>。</p>
</div><!-- .comment-content -->
<div class="reply">
<a rel="nofollow" class="comment-reply-link"
href="/p/1?replytocom=1#respond" data-commentid="1" data-postid="1"
data-belowelement="div-comment-1" data-respondelement="respond"
data-replyto="回复给一位WordPress评论者"
aria-label="回复给一位WordPress评论者">回复</a>
</div>
</article><!-- .comment-body -->
</li><!-- #comment-## -->
</ol><!-- .comment-list -->
{{if .canComment}}
<div id="respond" class="comment-respond">
<h3 id="reply-title" class="comment-reply-title">发表回复
<small>
<a rel="nofollow" id="cancel-comment-reply-link" href="/p/{{.post.Id}}#respond" style="display:none;">取消回复</a>
</small>
</h3>
<form action="/wp-comments-post.php" method="post" id="commentform" class="comment-form"
novalidate="">
<p class="comment-notes">
<span id="email-notes">您的电子邮箱地址不会被公开。</span>
<span class="required-field-message" aria-hidden="true">必填项已用<span class="required" aria-hidden="true">*</span>标注</span>
</p>
<p class="comment-form-comment">
<label for="comment">评论 <span class="required" aria-hidden="true">*</span></label>
<textarea id="comment" name="comment" cols="45" rows="8" maxlength="65525" required=""></textarea></p>
<p class="comment-form-author">
<label for="author">显示名称 <span class="required" aria-hidden="true">*</span></label>
<input id="author" name="author" type="text" value="" size="30" maxlength="245"
required=""></p>
<p class="comment-form-email">
<label for="email">电子邮箱地址 <span class="required" aria-hidden="true">*</span></label>
<input id="email" name="email" type="email" value="" size="30" maxlength="100"
aria-describedby="email-notes" required="">
</p>
<p class="comment-form-url"><label for="url">网站地址</label>
<input id="url" name="url" type="url" value="" size="30" maxlength="200"></p>
<p class="comment-form-cookies-consent">
<input id="wp-comment-cookies-consent" name="wp-comment-cookies-consent" type="checkbox" value="yes">
<label for="wp-comment-cookies-consent">在此浏览器中保存我的显示名称、邮箱地址和网站地址,以便下次评论时使用。</label>
</p>
<p class="form-submit">
<input name="submit" type="submit" id="submit" class="submit" value="发表评论">
<input type="hidden" name="comment_post_ID" value="{{.post.Id}}" id="comment_post_ID">
<input type="hidden" name="comment_parent" id="comment_parent" value="0">
</p>
</form>
</div><!-- #respond -->
{{end}} {{end}}
</footer> </div><!-- .comments-area -->
<!-- .entry-footer -->
</article><!-- #post-1 --> <nav class="navigation post-navigation" aria-label="文章">
<h2 class="screen-reader-text">文章导航</h2>
<div id="comments" class="comments-area"> <div class="nav-links">
{{if gt .prev.Id 0}}
<h2 class="comments-title"> <div class="nav-previous">
《{{.post.PostTitle}}》上有1条评论 </h2> <a href="/p/{{.prev.Id}}" rel="prev">
<span class="meta-nav" aria-hidden="true">上一篇</span>
<span class="screen-reader-text">上篇文章:</span>
<ol class="comment-list"> <span class="post-title">{{.prev.PostTitle}}</span></a>
<li id="comment-1" class="comment even thread-even depth-1">
<article id="div-comment-1" class="comment-body">
<footer class="comment-meta">
<div class="comment-author vcard">
<img alt=""
src="http://1.gravatar.com/avatar/d7a973c7dab26985da5f961be7b74480?s=56&amp;d=mm&amp;r=g"
srcset="http://1.gravatar.com/avatar/d7a973c7dab26985da5f961be7b74480?s=112&amp;d=mm&amp;r=g 2x"
class="avatar avatar-56 photo" height="56" width="56" loading="lazy">
<b class="fn">
<a href="https://cn.wordpress.org/" rel="external nofollow ugc"
class="url">一位WordPress评论者</a>
</b>
<span class="says">说道:</span></div><!-- .comment-author -->
<div class="comment-metadata">
<a href="/p/1#comment-1">
<time datetime="2022-08-19T09:26:37+08:00">2022年 8月 19日 上午9:26</time>
</a></div><!-- .comment-metadata -->
</footer><!-- .comment-meta -->
<div class="comment-content">
<p>您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 <a
href="https://cn.gravatar.com/">Gravatar</a>。</p>
</div><!-- .comment-content -->
<div class="reply">
<a rel="nofollow" class="comment-reply-link"
href="/p/1?replytocom=1#respond" data-commentid="1" data-postid="1"
data-belowelement="div-comment-1" data-respondelement="respond"
data-replyto="回复给一位WordPress评论者"
aria-label="回复给一位WordPress评论者">回复</a>
</div> </div>
</article><!-- .comment-body --> {{end}}
</li><!-- #comment-## --> {{if gt .next.Id 0}}
</ol><!-- .comment-list --> <div class="nav-next">
<a href="/p/{{.next.Id}}" rel="next">
<span class="meta-nav" aria-hidden="true">下一篇</span>
<span class="screen-reader-text">下篇文章:</span>
<span class="post-title">{{.next.PostTitle}}</span></a>
</div>
{{end}}
{{if .canComment}} </div>
<div id="respond" class="comment-respond"> </nav>
<h3 id="reply-title" class="comment-reply-title">发表回复 </main><!-- .site-main -->
<small> </div>
<a rel="nofollow" id="cancel-comment-reply-link" href="/p/{{.post.Id}}#respond" style="display:none;">取消回复</a> {{else}}
</small> {{template "layout/empty"}}
</h3> {{end }}
<form action="/wp-comments-post.php" method="post" id="commentform" class="comment-form"
novalidate="">
<p class="comment-notes">
<span id="email-notes">您的电子邮箱地址不会被公开。</span>
<span class="required-field-message" aria-hidden="true">必填项已用<span class="required" aria-hidden="true">*</span>标注</span>
</p>
<p class="comment-form-comment">
<label for="comment">评论 <span class="required" aria-hidden="true">*</span></label>
<textarea id="comment" name="comment" cols="45" rows="8" maxlength="65525" required=""></textarea></p>
<p class="comment-form-author">
<label for="author">显示名称 <span class="required" aria-hidden="true">*</span></label>
<input id="author" name="author" type="text" value="" size="30" maxlength="245"
required=""></p>
<p class="comment-form-email">
<label for="email">电子邮箱地址 <span class="required" aria-hidden="true">*</span></label>
<input id="email" name="email" type="email" value="" size="30" maxlength="100"
aria-describedby="email-notes" required="">
</p>
<p class="comment-form-url"><label for="url">网站地址</label>
<input id="url" name="url" type="url" value="" size="30" maxlength="200"></p>
<p class="comment-form-cookies-consent">
<input id="wp-comment-cookies-consent" name="wp-comment-cookies-consent" type="checkbox" value="yes">
<label for="wp-comment-cookies-consent">在此浏览器中保存我的显示名称、邮箱地址和网站地址,以便下次评论时使用。</label>
</p>
<p class="form-submit">
<input name="submit" type="submit" id="submit" class="submit" value="发表评论">
<input type="hidden" name="comment_post_ID" value="{{.post.Id}}" id="comment_post_ID">
<input type="hidden" name="comment_parent" id="comment_parent" value="0">
</p>
</form>
</div><!-- #respond -->
{{end}}
</div><!-- .comments-area -->
<nav class="navigation post-navigation" aria-label="文章">
<h2 class="screen-reader-text">文章导航</h2>
<div class="nav-links">
{{if gt .prev.Id 0}}
<div class="nav-previous">
<a href="/p/{{.prev.Id}}" rel="prev">
<span class="meta-nav" aria-hidden="true">上一篇</span>
<span class="screen-reader-text">上篇文章:</span>
<span class="post-title">{{.prev.PostTitle}}</span></a>
</div>
{{end}}
{{if gt .next.Id 0}}
<div class="nav-next">
<a href="/p/{{.next.Id}}" rel="next">
<span class="meta-nav" aria-hidden="true">下一篇</span>
<span class="screen-reader-text">下篇文章:</span>
<span class="post-title">{{.next.PostTitle}}</span></a>
</div>
{{end}}
</div>
</nav>
</main><!-- .site-main -->
</div>
{{end}} {{end}}