From bdaeb548192ba7cc2e6d15d30a15b6e03d63c66d Mon Sep 17 00:00:00 2001 From: Penryn <15158052130@163.com> Date: Mon, 4 Nov 2024 12:35:08 +0800 Subject: [PATCH] =?UTF-8?q?perf(room):=20=E5=A2=9E=E5=8A=A0=E7=A9=BA?= =?UTF-8?q?=E6=95=99=E5=AE=A4=E6=9F=A5=E8=AF=A2=E6=8E=A5=E5=8F=A3=E7=9A=84?= =?UTF-8?q?=E7=BC=93=E5=AD=98=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../zfController/zfController.go | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/app/controllers/funcControllers/zfController/zfController.go b/app/controllers/funcControllers/zfController/zfController.go index fce7000..9c3a746 100644 --- a/app/controllers/funcControllers/zfController/zfController.go +++ b/app/controllers/funcControllers/zfController/zfController.go @@ -1,6 +1,8 @@ package zfController import ( + "encoding/json" + "fmt" "github.com/gin-gonic/gin" "math/rand" "time" @@ -10,6 +12,7 @@ import ( "wejh-go/app/services/sessionServices" "wejh-go/app/services/userServices" "wejh-go/app/utils" + "wejh-go/config/redis" ) type form struct { @@ -170,13 +173,38 @@ func GetRoom(c *gin.Context) { return } + // 使用 Redis 缓存键,包含查询参数 + cacheKey := fmt.Sprintf("room:%s:%s:%s:%s:%s:%s", postForm.Year, postForm.Term, postForm.Campus, postForm.Weekday, postForm.Week, postForm.Sections) + result, err := funnelServices.GetRoom(user, postForm.Year, postForm.Term, postForm.Campus, postForm.Weekday, postForm.Week, postForm.Sections, loginType) if err != nil { if err == apiException.NoThatPasswordOrWrong { userServices.DelPassword(user, loginType) + _ = c.AbortWithError(200, err) + return } _ = c.AbortWithError(200, err) return + } else if result == nil { + // 从 Redis 中获取缓存结果 + cachedResult, cacheErr := redis.RedisClient.Get(c, cacheKey).Result() + if cacheErr == nil && cachedResult != "" { + var result []map[string]interface{} + if err := json.Unmarshal([]byte(cachedResult), &result); err == nil { + utils.JsonSuccessResponse(c, result) + return + } + } else if cacheErr != nil { + _ = c.AbortWithError(200, apiException.ServerError) + return + } + } + // 将结果缓存到 Redis 中 + resultJson, _ := json.Marshal(result) + err = redis.RedisClient.Set(c, cacheKey, string(resultJson), 1*time.Hour).Err() + if err != nil { + _ = c.AbortWithError(200, apiException.ServerError) + return } utils.JsonSuccessResponse(c, result) }