From ca60f49cc95540aaf15b850d95fb6d450dd8a532 Mon Sep 17 00:00:00 2001 From: lifei6671 Date: Mon, 23 Jul 2018 16:25:39 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=96=87=E7=AB=A0=E7=BC=93?= =?UTF-8?q?=E5=AD=98=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controllers/BlogController.go | 2 +- models/Blog.go | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/controllers/BlogController.go b/controllers/BlogController.go index b16f1936..1a01ed2f 100644 --- a/controllers/BlogController.go +++ b/controllers/BlogController.go @@ -32,7 +32,7 @@ func (c *BlogController) Index() { } blogReadSession := fmt.Sprintf("blog:read:%d",blogId) - blog,err := models.NewBlog().Find(blogId) + blog,err := models.NewBlog().FindFromCache(blogId) if err != nil { c.ShowErrorPage(404,"文章不存在") diff --git a/models/Blog.go b/models/Blog.go index b0c2a737..48cd1852 100644 --- a/models/Blog.go +++ b/models/Blog.go @@ -5,6 +5,8 @@ import ( "github.com/lifei6671/mindoc/conf" "github.com/astaxie/beego/orm" "github.com/astaxie/beego" + "github.com/lifei6671/mindoc/cache" + "fmt" ) //博文表 @@ -94,6 +96,26 @@ func (b *Blog) Find(blogId int) (*Blog,error) { return b.Link() } + +//从缓存中读取文章 +func (b *Blog) FindFromCache(blogId int) (blog *Blog,err error) { + key := fmt.Sprintf("blog-id-%d",blogId); + obj := cache.Get(key) + + if b,ok := obj.(Blog); ok { + blog = &b + blog.Link() + return + } + blog,err = b.Find(blogId) + if err == nil { + //默认一个小时 + cache.Put(key,blog,time.Hour * 1) + } + return +} + + //查找指定用户的指定文章 func (b *Blog) FindByIdAndMemberId(blogId,memberId int) (*Blog,error) { o := orm.NewOrm() @@ -191,6 +213,9 @@ func (b *Blog) Save(cols ...string) error { if b.BlogId > 0 { b.Modified = time.Now() _,err = o.Update(b,cols...) + key := fmt.Sprintf("blog-id-%d",b.BlogId); + cache.Delete(key) + }else{ b.Created = time.Now()