-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash_online_storage.go
80 lines (61 loc) · 1.85 KB
/
hash_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
package research_online_redis_go
import (
"context"
"strconv"
"github.com/redis/go-redis/v9"
)
type HashOnlineStorage struct {
client *redis.Client
}
func NewHashOnlineStorage(client *redis.Client) *HashOnlineStorage {
return &HashOnlineStorage{client: client}
}
func (s *HashOnlineStorage) Store(ctx context.Context, pair UserOnlinePair) error {
return s.client.HSet(ctx, "h:online:main", strconv.FormatInt(pair.UserID, 10), pair.Timestamp).Err()
}
func (s *HashOnlineStorage) BatchStore(ctx context.Context, pairs []UserOnlinePair) error {
values := make([]interface{}, 0, len(pairs)*2)
for _, pair := range pairs {
values = append(values, pair.Timestamp, pair.UserID)
}
return s.client.HSet(ctx, "h:online:main", values).Err()
}
func (s *HashOnlineStorage) Count(ctx context.Context) (int64, error) {
return s.client.HLen(ctx, "h:online:main").Result()
}
func (s *HashOnlineStorage) GetAndClear(ctx context.Context) ([]UserOnlinePair, error) {
var (
oldKey = "h:online:main"
newKey = "h:online:tmp"
)
err := s.client.Rename(ctx, oldKey, newKey).Err()
if err != nil {
return nil, err
}
userOnlineMap, err := s.client.HGetAll(ctx, newKey).Result()
if err != nil {
return nil, err
}
result := make([]UserOnlinePair, 0, len(userOnlineMap))
for stringUserID, stringTimestamp := range userOnlineMap {
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
}
timestamp, err := strconv.ParseInt(stringTimestamp, 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: timestamp,
})
}
return result, nil
}