feat(lyra)!: 接入 Redis 并添加缓存连通性实验
- 封装缓存读写、JSON 编解码、过期时间与操作超时 - 集中组装 Redis 依赖,在测试接口验证分类缓存读写 - 更新依赖并移除原 handler 测试 BREAKING CHANGE: 配置节由 redis 改为 cache,新增 db 和 timeout 配置项
This commit is contained in:
@@ -1,30 +1,56 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"lyra/internal/api"
|
||||
"lyra/internal/cache"
|
||||
"lyra/internal/httpx"
|
||||
"lyra/internal/model"
|
||||
"net/http"
|
||||
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type TestHandler struct {
|
||||
categoryModel model.CategoryModel
|
||||
cache *cache.Cache
|
||||
}
|
||||
|
||||
func NewTestHandler(categoryModel model.CategoryModel) *TestHandler {
|
||||
return &TestHandler{categoryModel: categoryModel}
|
||||
func NewTestHandler(categoryModel model.CategoryModel, cache *cache.Cache) *TestHandler {
|
||||
return &TestHandler{categoryModel: categoryModel, cache: cache}
|
||||
}
|
||||
|
||||
func (h *TestHandler) Hello() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
categories, err := h.categoryModel.FindAll(c.Request.Context())
|
||||
return func(ctx *gin.Context) {
|
||||
categories, err := h.categoryModel.FindAll(ctx.Request.Context())
|
||||
if err != nil {
|
||||
httpx.Fail(c, http.StatusInternalServerError, api.CodeInternalError, "获取分类列表失败")
|
||||
httpx.Fail(ctx, http.StatusInternalServerError, api.CodeInternalError, "获取分类列表失败")
|
||||
return
|
||||
}
|
||||
httpx.OK(c, toCategoryResponses(categories))
|
||||
if err := h.cache.Set(ctx.Request.Context(), cache.Entry[[]*model.Category]{
|
||||
Key: "test:categories",
|
||||
Value: categories,
|
||||
TTL: 5 * time.Minute,
|
||||
}); err != nil {
|
||||
slog.ErrorContext(ctx.Request.Context(), "缓存分类列表失败")
|
||||
return
|
||||
}
|
||||
testResult, _, err := h.cache.Get[[]*model.Category](ctx.Request.Context(), "test:categories")
|
||||
if err != nil {
|
||||
slog.ErrorContext(ctx.Request.Context(), "获取缓存分类列表失败")
|
||||
}
|
||||
if len(testResult) == 0 {
|
||||
slog.ErrorContext(ctx.Request.Context(), "缓存分类列表为空")
|
||||
} else {
|
||||
for _, v := range testResult {
|
||||
fmt.Printf("%+v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
httpx.OK(ctx, toCategoryResponses(categories))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user