Files
epic-go/internal/logic/hero/hero.go
hxt 61cb21fdc7 refactor(cache): 抽离 Redis 缓存初始化逻辑
- 新增 utility/cache.go 文件,定义全局的 RedisCache 变量
- 修改 hero.go 中的缓存使用方式,使用新的 RedisCache 全局变量
- 更新 main.go,移除冗余的包引用
2025-06-21 23:06:45 +08:00

100 lines
2.2 KiB
Go

package hero
import (
"context"
v1 "epic/api/hero/v1"
"epic/internal/dao"
"epic/internal/model/entity"
"epic/internal/service"
"epic/utility"
"fmt"
"github.com/gogf/gf/v2/frame/g"
"time"
)
type Logic struct{}
func New() *Logic {
return &Logic{}
}
func init() {
service.SetHero(New())
}
// GetHeroByCode 根据 code 获取英雄信息
func (l *Logic) GetHeroByCode(ctx context.Context, code string) (*entity.EpicHeroInfo, error) {
// 2. 缓存未命中,查数据库
var hero *entity.EpicHeroInfo
err := dao.EpicHeroInfo.Ctx(ctx).
Where(dao.EpicHeroInfo.Columns().HeroCode, code).
Scan(&hero)
if err != nil {
return nil, err
}
return hero, nil
}
// GetHeroList 查询所有英雄信息,并按创建时间倒序排列
func (l *Logic) GetHeroList(ctx context.Context) ([]*v1.EpicHeroVO, error) {
utility.RedisCache.Set(ctx, "epic_artifact_map_key111", "122", 1000*time.Second)
utility.RedisCache.Set(ctx, "epic_artifact_map_key222", "6565", 0)
fmt.Println(utility.RedisCache.Get(ctx, "NAME"))
var (
doList []*entity.EpicHeroInfo // 数据库原始结构
voList []*v1.EpicHeroVO // 要返回的视图结构
)
// 2. 缓存未命中,查数据库
err := dao.EpicHeroInfo.Ctx(ctx).
OrderDesc(dao.EpicHeroInfo.Columns().CreateTime). // 按创建时间倒序
Scan(&doList)
if err != nil {
return nil, err
}
// 3. 手动映射 DO -> VO
for _, hero := range doList {
voList = append(voList, &v1.EpicHeroVO{
Id: hero.Id,
HeroName: hero.HeroName,
HeroCode: hero.HeroCode,
Attribute: hero.Attribute,
HeadImgUrl: hero.HeadImgUrl,
HeroAttrLv60: hero.HeroAttrLv60,
NickName: hero.NickName,
Rarity: hero.Rarity,
Role: hero.Role,
Zodiac: hero.Zodiac,
Remark: hero.Remark,
})
}
return voList, nil
}
func (l *Logic) GetHeroDetailByCode(ctx context.Context, code string) (*v1.HeroDetailVO, error) {
//TODO implement me
panic("implement me")
}
// ClearHeroCache 清理英雄相关缓存
func (l *Logic) ClearHeroCache(ctx context.Context, code string) error {
redis := g.Redis()
// 清理单个英雄缓存
if code != "" {
cacheKey := "hero:" + code
redis.Del(ctx, cacheKey)
}
// 清理英雄列表缓存
redis.Del(ctx, "hero:list")
return nil
}