redis 保存最新记录

日常开发中经常会遇到需要展示最新几条记录的需求,这个一般也都是比较热数据,存放在缓存是一个不错的高效率解决方案。

这个就要用到redis的列表List。

使用Ltrim保持固定的长度的:

	//更新最新列表
	key = GetRedisExdLatestKey(countryCode)
	marshal, err := json.Marshal(winer)

	pipeline := radix.Pipeline(
		radix.FlatCmd(nil, "LPUSH", key, marshal),
		radix.FlatCmd(nil, "LTRIM", key, 0, 3))
	err = redisModel.DoCmd(redisModel.RedisDBName, pipeline)
	if err != nil {
		xlog.LevelLogfn(xlog.ERROR, "[UpdateDifCountryExCount] DoCmd err =%+v", err)
	}

取出:

	key := GetRedisExdLatestKey(countryCode)
	winners = make([]*pb2.Winner, 0)
	var winStr []string
	pipeline := radix.Pipeline(radix.FlatCmd(&winStr, "LRANGE", key, 0, -1))
	err = redisModel.DoCmd(redisModel.RedisDBName, pipeline)
	if err != nil {
		xlog.LevelLogfn(xlog.ERROR, "[UpdateDifCountryExCount] LRANGE err =%+v", err)
	} else if len(winStr) > 3 {
		return WinStrconvEntity(winStr)
	}

转换:

func WinStrconvEntity(winStr []string) (winners []*pb2.Winner, err error) {
	winners = make([]*pb2.Winner, 0)
	for _, v := range winStr {
		bytes := []byte(v)
		winner := &pb2.Winner{}
		err = json.Unmarshal(bytes, winner)
		if err != nil {
			xlog.LevelLogfn(xlog.ERROR, "[UpdateDifCountryExCount] Unmarshal err =%+v", err)
		}
		winners = append(winners, winner)
	}
	return
}

 

你可能感兴趣的:(redis)