1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| package main
import ( "bytes" "context" "encoding/binary" "fmt" "math" "time"
"github.com/go-redis/redis/v8" )
const ( MAX_MEMBER_COUNT int16 = 250 MAX_32BIT_INT int32 = int32(math.MaxInt32) )
type ScoreInfo struct { Score int16 MemberCount int16 ClearDt int32 }
func (s ScoreInfo) SaveScore() float64 { buf := new(bytes.Buffer)
binary.Write(buf, binary.BigEndian, s.Score) binary.Write(buf, binary.BigEndian, MAX_MEMBER_COUNT-s.MemberCount) binary.Write(buf, binary.BigEndian, MAX_32BIT_INT-s.ClearDt) return math.Float64frombits(binary.BigEndian.Uint64(buf.Bytes())) }
func (s ScoreInfo) ReadScore(redisScore float64) ScoreInfo { buf := new(bytes.Buffer) binary.Write(buf, binary.BigEndian, math.Float64bits(redisScore)) s.Score = int16(binary.BigEndian.Uint16(buf.Bytes()[0:2])) s.MemberCount = MAX_MEMBER_COUNT - int16(binary.BigEndian.Uint16(buf.Bytes()[2:4])) s.ClearDt = MAX_32BIT_INT - int32(binary.BigEndian.Uint32(buf.Bytes()[4:8]))
return s }
func main() { client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", DB: 0, })
err := client.Ping(context.Background()).Err() if err != nil { panic(err) }
scoreInfo := ScoreInfo{ Score: 23346, MemberCount: 230, ClearDt: int32(time.Now().Unix()), }
fmt.Println("prevScoreInfo: ", scoreInfo)
saveScore := scoreInfo.SaveScore()
err = client.ZAdd(context.Background(), "RankKey4", &redis.Z{ Score: saveScore, Member: "a", }).Err()
scoreInfo2 := ScoreInfo{ Score: 32130, MemberCount: 134, ClearDt: int32(time.Date(2023, time.June, 2, 0, 0, 0, 0, time.UTC).Unix()), }
fmt.Println("prevScoreInfo2: ", scoreInfo2)
saveScore = scoreInfo2.SaveScore()
err = client.ZAdd(context.Background(), "RankKey4", &redis.Z{ Score: saveScore, Member: "b", }).Err()
result, err := client.ZRevRangeWithScores(context.Background(), "RankKey4", 0, -1).Result() if err != nil { panic(err) }
for _, z := range result { updateScoreInfo := scoreInfo.ReadScore(z.Score) fmt.Println("member:", z.Member, "afterScoreInfo:", updateScoreInfo) } }
|