Sfoglia il codice sorgente

feat: 缓存友情链接列表

runningwater 5 mesi fa
parent
commit
7cc0a0542c

+ 1 - 1
app/http/controllers/api/v1/links_controller.go

@@ -12,6 +12,6 @@ type LinksController struct {
 }
 
 func (ctrl *LinksController) Index(c *gin.Context) {
-	links := link.All()
+	links := link.AllCached()
 	response.Data(c, links)
 }

+ 20 - 0
app/models/link/link_util.go

@@ -1,10 +1,14 @@
 package link
 
 import (
+	"time"
+
 	"github.com/gin-gonic/gin"
 
 	"github.com/runningwater/gohub/pkg/app"
+	"github.com/runningwater/gohub/pkg/cache"
 	"github.com/runningwater/gohub/pkg/database"
+	"github.com/runningwater/gohub/pkg/helpers"
 	"github.com/runningwater/gohub/pkg/paginator"
 )
 
@@ -23,6 +27,22 @@ func All() (links []Link) {
 	return
 }
 
+func AllCached() (links []Link) {
+	cacheKey := "links:aa"
+	expireTime := 120 * time.Minute
+	// 获取数据
+	cache.GetObject(cacheKey, &links)
+
+	if helpers.Empty(links) {
+		links = All()
+		if helpers.Empty(links) {
+			return links
+		}
+		cache.Set(cacheKey, links, expireTime)
+	}
+	return
+}
+
 func IsExist(field, value string) bool {
 	var count int64
 	database.DB.Model(Link{}).Where("? = ?", field, value).Count(&count)