利用 redis
zset
实现排行榜,基于 得分+时间
二个纬度排行, 定义一个最大值减去当前时间戳 再加上分数,得到最后的分数。
有一个不足的地方就是不能使用 redis
自带的 ZINCRBY
去原子操作。可以使用 阿里云的 TairZset
(opens new window) 多维度去解决。
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/go-redis/redis/v8"
"math/rand"
"net/http"
"strconv"
"time"
)
const MAX int = 1671552000
var (
conn *redis.Client
)
func init() {
conn = redisConnect()
}
func main() {
defer conn.Close()
http.HandleFunc("/init", initHandler)
http.HandleFunc("/add", addHandler)
http.HandleFunc("/rank", rankHandler)
_ = http.ListenAndServe("127.0.0.1:8000", nil)
}
func redisConnect() *redis.Client {
rdb := redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379",
Password: "xxxxx",
DB: 15,
//连接池容量及闲置连接数量
PoolSize: 100, // 连接池最大socket连接数,默认为4倍CPU数, 4 * runtime.NumCPU
MinIdleConns: 10, //在启动阶段创建指定数量的Idle连接,并长期维持idle状态的连接数不少于指定数量;。
})
fmt.Println("connect redis success!")
return rdb
}
func addHandler(w http.ResponseWriter, r *http.Request) {
nowTimestamp := int(time.Now().Unix())
score := rand.Intn(10000)
scoreStr := strconv.Itoa(score)
diff := MAX - nowTimestamp
Score, _ := strconv.ParseFloat(scoreStr+"."+strconv.Itoa(diff), 64)
ls := redis.Z{
Score: Score,
Member: "姓名" + scoreStr,
}
ctx := context.Background()
conn.ZAdd(ctx, "ranking", &ls)
_, _ = w.Write([]byte("OK"))
}
func initHandler(w http.ResponseWriter, r *http.Request) {
ls := []*redis.Z{
{Score: 90.0, Member: "one"},
{Score: 80.0, Member: "two"},
{Score: 70.0, Member: "three"},
{Score: 60.0, Member: "four"},
{Score: 50.0, Member: "five"},
}
ctx := context.Background()
conn.ZAdd(ctx, "ranking", ls...)
_, _ = w.Write([]byte("OK"))
}
func rankHandler(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
list := conn.ZRevRangeWithScores(ctx, "ranking", 0, -1).Val()
jsons, errs := json.Marshal(list)
if errs != nil {
fmt.Println("json marshal error:", errs)
}
fmt.Println(string(jsons))
w.Header().Set("content-type", "text/json")
_, _ = w.Write(jsons)
}
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
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