redis_cache.go 1.7 KB
package cache

import (
	"fmt"
	"github.com/linmadan/egglib-go/utils/json"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/constant"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/redis"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/log"
)

type DataTableRedisCacheService struct {
}

func (svr *DataTableRedisCacheService) KeyDataTable(tableId int) string {
	return fmt.Sprintf("%s:cache:table:%d", constant.CACHE_PREFIX, tableId)
}

func (svr *DataTableRedisCacheService) GetDataTable(tableId int) (*domain.DataTable, bool) {
	key := svr.KeyDataTable(tableId)
	data, err := redis.ZeroCoreRedis.Get(key)
	if err == redis.NotFound || len(data) == 0 {
		log.Logger.Info(fmt.Sprintf("【缓存】 miss cache %v", key))
		return nil, false
	}
	var table = &domain.DataTable{}
	err = json.UnmarshalFromString(data, table)
	if err != nil {
		log.Logger.Error(fmt.Sprintf("【缓存】 miss cache %v,err %v", key, err.Error()))
		return nil, false
	}
	log.Logger.Info(fmt.Sprintf("【缓存】 hit cache %v", key))
	return table, true
}

func (svr *DataTableRedisCacheService) SetDataTable(tableId int, table *domain.DataTable) {
	key := svr.KeyDataTable(tableId)
	log.Logger.Info(fmt.Sprintf("【缓存】 set cache %v", key))
	redis.ZeroCoreRedis.Setex(key, json.MarshalToString(table), TableCacheExpire)
}

func (svr *DataTableRedisCacheService) DeleteDataTable(tableId int) {
	key := svr.KeyDataTable(tableId)
	log.Logger.Info(fmt.Sprintf("【缓存】 delete cache %v", key))
	redis.ZeroCoreRedis.Del(key)
}