87bdad34fc
- 修改`.env.example`文件,更新数据库和Redis的默认主机地址为`192.168.9.127` - 在`docker-compose.yml`中移除不必要的卷挂载配置 - 在`go.mod`中添加`github.com/joho/godotenv`依赖以支持环境变量加载 - 更新`README.md`以反映新的数据库和Redis连接信息 - 在`main.go`中加载环境变量以支持动态配置 - 新增缓存存在性检查功能,避免重复预热缓存 - 优化CSV读取逻辑,支持从S3获取数据
53 lines
1.1 KiB
Go
53 lines
1.1 KiB
Go
package cache
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/luxsin/app-api/internal/model"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
const (
|
|
brandAllKey = "brand:all"
|
|
brandTTL = 30 * time.Minute
|
|
)
|
|
|
|
type BrandCache struct {
|
|
rdb *redis.Client
|
|
}
|
|
|
|
func NewBrandCache(rdb *redis.Client) *BrandCache {
|
|
return &BrandCache{rdb: rdb}
|
|
}
|
|
|
|
func (c *BrandCache) Exists(ctx context.Context) (bool, error) {
|
|
n, err := c.rdb.Exists(ctx, brandAllKey).Result()
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return n > 0, nil
|
|
}
|
|
|
|
func (c *BrandCache) GetAll(ctx context.Context) ([]model.Brand, error) {
|
|
data, err := c.rdb.Get(ctx, brandAllKey).Bytes()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var list []model.Brand
|
|
if err := json.Unmarshal(data, &list); err != nil {
|
|
return nil, fmt.Errorf("unmarshal brands: %w", err)
|
|
}
|
|
return list, nil
|
|
}
|
|
|
|
func (c *BrandCache) SetAll(ctx context.Context, list []model.Brand) error {
|
|
data, err := json.Marshal(list)
|
|
if err != nil {
|
|
return fmt.Errorf("marshal brands: %w", err)
|
|
}
|
|
return c.rdb.Set(ctx, brandAllKey, data, brandTTL).Err()
|
|
}
|