新增功能
This commit is contained in:
+39
-4
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -10,12 +11,14 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/luxsin/app-api/internal/cache"
|
||||
"github.com/luxsin/app-api/internal/config"
|
||||
"github.com/luxsin/app-api/internal/database"
|
||||
"github.com/luxsin/app-api/internal/cache"
|
||||
"github.com/luxsin/app-api/internal/repository"
|
||||
"github.com/luxsin/app-api/internal/router"
|
||||
"github.com/luxsin/app-api/internal/search"
|
||||
"github.com/luxsin/app-api/pkg/logger"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
@@ -53,15 +56,18 @@ func main() {
|
||||
zap.String("index", cfg.Meilisearch.Index),
|
||||
)
|
||||
|
||||
redisClient := cache.NewClient(cfg.Redis)
|
||||
defer redisClient.Close()
|
||||
rdb := cache.NewClient(cfg.Redis)
|
||||
defer rdb.Close()
|
||||
log.Info("redis connected",
|
||||
zap.String("host", cfg.Redis.Host),
|
||||
zap.Int("port", cfg.Redis.Port),
|
||||
zap.Int("db", cfg.Redis.Database),
|
||||
)
|
||||
|
||||
engine := router.New(log, db, searchClient, redisClient)
|
||||
// 启动时预热缓存
|
||||
warmUpCache(log, db, rdb)
|
||||
|
||||
engine := router.New(log, db, searchClient, rdb)
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: cfg.Addr(),
|
||||
@@ -93,3 +99,32 @@ func main() {
|
||||
|
||||
log.Info("server stopped")
|
||||
}
|
||||
|
||||
// warmUpCache 启动时从数据库加载数据到 Redis
|
||||
func warmUpCache(log *zap.Logger, db *sql.DB, rdb *redis.Client) {
|
||||
ctx := context.Background()
|
||||
|
||||
brandCache := cache.NewBrandCache(rdb)
|
||||
modelCache := cache.NewModelCache(rdb)
|
||||
|
||||
brandRepo := repository.NewBrandRepository(db, brandCache)
|
||||
modelRepo := repository.NewModelRepository(db, modelCache)
|
||||
|
||||
// 预热 brand:all
|
||||
if brands, err := brandRepo.ListFromDB(ctx, ""); err != nil {
|
||||
log.Warn("brand warm-up failed", zap.Error(err))
|
||||
} else if err := brandCache.SetAll(ctx, brands); err != nil {
|
||||
log.Warn("brand cache set failed", zap.Error(err))
|
||||
} else {
|
||||
log.Info("brand cache warmed up", zap.Int("count", len(brands)))
|
||||
}
|
||||
|
||||
// 预热 model:all
|
||||
if allModels, err := modelRepo.ListAllFromDB(ctx); err != nil {
|
||||
log.Warn("model warm-up failed", zap.Error(err))
|
||||
} else if err := modelCache.SetAll(ctx, allModels); err != nil {
|
||||
log.Warn("model cache set failed", zap.Error(err))
|
||||
} else {
|
||||
log.Info("model cache warmed up", zap.Int("count", len(allModels)))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user