golang 实现redis 排行榜同分值情况下按时间升序排序

在排行榜中实现分数和时间排序 分数相同则按照时间排序
需求分析
  • redis中zset的long为int64 转为十进制是19位
  • 时间戳10位 毫秒时间戳13位 高位存分数7位 十进制 7位
  • 8字节中拆分 最高位不可用 还剩43位 高22位存分数 低41位存时间戳
golang 代码
package main

import (
	"fmt"
	"sort"
	"time"
)

var scores []int64

func main() {
	sorts()
	//bit()
}

func bit() {
	fmt.Println(len(fmt.Sprintf("%d", 1<<9)))
	fmt.Println(len(fmt.Sprintf("%d", 1<<41)))
	fmt.Println(len(fmt.Sprintf("%d", 1<<23)))
	fmt.Println(len("1000000"))
}

func sorts() {
	now := time.Now().UnixMilli()
	for i := 1; i < 10; i++ {
		scores = append(scores, toScore(int64(i+100000), now))
	}

	sort.Slice(scores, func(i, j int) bool {
		return scores[i] > scores[j]
	})
	for _, score := range scores {
		fmt.Println(load(score))
		//fmt.Println(score)
	}
}

func toScore(point int64, periodEndTimestamp int64) (score int64) {
	score = (score | point) << 41
	score = score | periodEndTimestamp
	return
}

func load(score int64) int64 {
	return score >> 41
}

posted @ 2022-05-17 22:22  vx_guanchaoguo0  阅读(539)  评论(0编辑  收藏  举报