-
Notifications
You must be signed in to change notification settings - Fork 0
/
sorted_set_online_storage.go
84 lines (66 loc) · 1.88 KB
/
sorted_set_online_storage.go
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
package research_online_redis_go
import (
"context"
"strconv"
"github.com/redis/go-redis/v9"
)
type SortedSetOnlineStorage struct {
client *redis.Client
}
func NewSortedSetOnlineStorage(client *redis.Client) *SortedSetOnlineStorage {
return &SortedSetOnlineStorage{client: client}
}
func (s *SortedSetOnlineStorage) Store(ctx context.Context, pair UserOnlinePair) error {
return s.client.ZAdd(ctx, "z:online:main", redis.Z{
Score: float64(pair.Timestamp),
Member: strconv.FormatInt(pair.UserID, 10),
}).Err()
}
func (s *SortedSetOnlineStorage) BatchStore(ctx context.Context, pairs []UserOnlinePair) error {
members := make([]redis.Z, len(pairs))
for i, pair := range pairs {
members[i] = redis.Z{
Score: float64(pair.Timestamp),
Member: strconv.FormatInt(pair.UserID, 10),
}
}
return s.client.ZAdd(ctx, "z:online:main", members...).Err()
}
func (s *SortedSetOnlineStorage) Count(ctx context.Context) (int64, error) {
return s.client.ZCard(ctx, "z:online:main").Result()
}
func (s *SortedSetOnlineStorage) GetAndClear(ctx context.Context) ([]UserOnlinePair, error) {
var (
oldKey = "z:online:main"
newKey = "z:online:tmp"
)
err := s.client.Rename(ctx, oldKey, newKey).Err()
if err != nil {
return nil, err
}
members, err := s.client.ZRangeWithScores(ctx, newKey, 0, -1).Result()
if err != nil {
return nil, err
}
result := make([]UserOnlinePair, 0, len(members))
for _, member := range members {
stringUserID, ok := member.Member.(string)
if !ok {
// unreachable, ignore for article
// just in case
continue
}
userID, err := strconv.ParseInt(stringUserID, 10, 64)
if err != nil {
// unreachable, ignore for article
// logging or use https://github.com/hashicorp/go-multierror
// just in case
continue
}
result = append(result, UserOnlinePair{
UserID: userID,
Timestamp: int64(member.Score),
})
}
return result, nil
}