参考文献

golang redis hash教程
Go语言操作Redis

环境说明

  • go version go1.16.2 darwin/amd64
  • redis github.com/go-redis/redis/v8

步骤说明

# 在项目目录下初始化 go mod
go mod init
# 下载 go-redis 依赖
go get github.com/go-redis/redis/v8

SAdd

示例:

robotIdsKey := "axinblog:robot_ids"
var args []interface{}

for _, item := range res.Members {
        args = append(args, item.Id)
}

_, err = s.dao.Redis.SAdd(ctx, robotIdsKey, args...).Result()
if err != nil {
    log.Error("PkGameSVC.PkGameJoinAllRobot SAdd error(%s)", args, err)
    return
}

ZRevRange

示例:

var rankColl []string
rankColl, err = d.Redis.ZRevRange(ctx, rankKey, 0, -1).Result()
if err != nil {
    panic(err)
}

Expire

示例:

rankKey := "axinblog:rank"
existsStatus, err := d.Redis.Exists(ctx, rankKey).Result()
currentTime := time.Now()
expirationTime := currentTime.AddDate(0, 0, 3).Sub(currentTime)
d.Redis.ZIncrBy(ctx, rankKey, constant.FirstValue, strconv.FormatInt(winMemberId, 10))
if !(existsStatus > constant.ZeroValue) {
    d.Redis.Expire(ctx, rankKey, expirationTime)
}