Skip to content

Commit

Permalink
perf(room): 增加空教室查询接口的缓存功能
Browse files Browse the repository at this point in the history
  • Loading branch information
Penryn committed Nov 4, 2024
1 parent c6d74cf commit 4fcd4c3
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions app/controllers/funcControllers/zfController/zfController.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package zfController

import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"math/rand"
"time"
Expand All @@ -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 {
Expand Down Expand Up @@ -170,12 +173,29 @@ 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)
// 从 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
}
_ = c.AbortWithError(200, err)
}
// 将结果缓存到 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)
Expand Down

0 comments on commit 4fcd4c3

Please sign in to comment.