-
Notifications
You must be signed in to change notification settings - Fork 0
/
go_online_storage.go
61 lines (46 loc) · 1.1 KB
/
go_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
package research_online_redis_go
import (
"context"
"sync"
)
type GoOnlineStorage struct {
mu sync.Mutex
data map[int64]int64
}
func NewGoOnlineStorage() *GoOnlineStorage {
return &GoOnlineStorage{
data: map[int64]int64{},
}
}
func (s *GoOnlineStorage) Store(ctx context.Context, pair UserOnlinePair) error {
s.mu.Lock()
defer s.mu.Unlock()
s.data[pair.UserID] = pair.Timestamp
return nil
}
func (s *GoOnlineStorage) BatchStore(ctx context.Context, pairs []UserOnlinePair) error {
s.mu.Lock()
defer s.mu.Unlock()
for _, pair := range pairs {
s.data[pair.UserID] = pair.Timestamp
}
return nil
}
func (s *GoOnlineStorage) Count(ctx context.Context) (int64, error) {
s.mu.Lock()
defer s.mu.Unlock()
return int64(len(s.data)), nil
}
func (s *GoOnlineStorage) GetAndClear(ctx context.Context) ([]UserOnlinePair, error) {
s.mu.Lock()
defer s.mu.Unlock()
result := make([]UserOnlinePair, 0, len(s.data))
for userID, timestamp := range s.data {
result = append(result, UserOnlinePair{
UserID: userID,
Timestamp: timestamp,
})
}
s.data = map[int64]int64{}
return result, nil
}