-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclusterrediscounter.go
44 lines (37 loc) · 1 KB
/
clusterrediscounter.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
package rediscounter
import (
"context"
"github.com/redis/go-redis/v9"
)
type ClusterRedisCounter struct {
counterKey string
client *redis.ClusterClient
}
func NewWithCluster(addrs []string, password string, counterKey string) *ClusterRedisCounter {
rdb := redis.NewClusterClient(&redis.ClusterOptions{
Addrs: addrs,
Password: password,
})
return &ClusterRedisCounter{client: rdb, counterKey: counterKey}
}
func NewWithClient(client *redis.ClusterClient, counterKey string) *ClusterRedisCounter {
return &ClusterRedisCounter{client: client, counterKey: counterKey}
}
func (rc *ClusterRedisCounter) Next() (uint64, error) {
var ctx = context.Background()
has, err := rc.client.Exists(ctx, rc.counterKey).Result()
if err != nil {
return 0, err
}
var next int64 = 0
if has == 1 {
next, err = rc.client.Incr(ctx, rc.counterKey).Result()
if err != nil {
return 0, err
}
return uint64(next), nil
} else {
_, err = rc.client.Set(ctx, rc.counterKey, 0, 0).Result()
return 0, err
}
}