From 61cb21fdc7d6741bfc82f3fcb8f96c5e12b3d7c3 Mon Sep 17 00:00:00 2001 From: hxt Date: Sat, 21 Jun 2025 23:06:45 +0800 Subject: [PATCH] =?UTF-8?q?refactor(cache):=20=E6=8A=BD=E7=A6=BB=20Redis?= =?UTF-8?q?=20=E7=BC=93=E5=AD=98=E5=88=9D=E5=A7=8B=E5=8C=96=E9=80=BB?= =?UTF-8?q?=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 utility/cache.go 文件,定义全局的 RedisCache 变量 - 修改 hero.go 中的缓存使用方式,使用新的 RedisCache 全局变量 - 更新 main.go,移除冗余的包引用 --- internal/logic/hero/hero.go | 14 ++++---------- main.go | 3 +-- utility/cache.go | 12 ++++++++++++ 3 files changed, 17 insertions(+), 12 deletions(-) create mode 100644 utility/cache.go diff --git a/internal/logic/hero/hero.go b/internal/logic/hero/hero.go index a2360a8..32013e8 100644 --- a/internal/logic/hero/hero.go +++ b/internal/logic/hero/hero.go @@ -6,9 +6,9 @@ import ( "epic/internal/dao" "epic/internal/model/entity" "epic/internal/service" + "epic/utility" "fmt" "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/os/gcache" "time" ) @@ -39,16 +39,10 @@ func (l *Logic) GetHeroByCode(ctx context.Context, code string) (*entity.EpicHer // GetHeroList 查询所有英雄信息,并按创建时间倒序排列 func (l *Logic) GetHeroList(ctx context.Context) ([]*v1.EpicHeroVO, error) { - // 推荐从配置文件加载 - redisClient := g.Redis() - cache := gcache.New() - cache.SetAdapter(gcache.NewAdapterRedis(redisClient)) - // Create redis cache adapter and set it to cache object. - //fmt.Println(cache.MustGet(ctx, "epic_artifact_map_key").String()) - cache.Set(ctx, "epic_artifact_map_key111", "545487878", 1000*time.Second) - cache.Set(ctx, "epic_artifact_map_key222", "5454878787878878", 0) - fmt.Println(cache.Get(ctx, "epic_artifact_map_key111")) + 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 // 数据库原始结构 diff --git a/main.go b/main.go index a196f97..3cafab5 100644 --- a/main.go +++ b/main.go @@ -1,13 +1,12 @@ package main import ( + "epic/internal/cmd" _ "epic/internal/logic" _ "epic/internal/packed" _ "github.com/gogf/gf/contrib/drivers/mysql/v2" _ "github.com/gogf/gf/contrib/nosql/redis/v2" "github.com/gogf/gf/v2/os/gctx" - - "epic/internal/cmd" ) func main() { diff --git a/utility/cache.go b/utility/cache.go new file mode 100644 index 0000000..d6e23ec --- /dev/null +++ b/utility/cache.go @@ -0,0 +1,12 @@ +package utility + +import ( + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/os/gcache" +) + +var RedisCache = func() *gcache.Cache { + cache := gcache.New() + cache.SetAdapter(gcache.NewAdapterRedis(g.Redis())) + return cache +}()