-
Notifications
You must be signed in to change notification settings - Fork 0
/
counter.go
82 lines (65 loc) · 1.58 KB
/
counter.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
package kredis
import "github.com/redis/go-redis/v9"
type Counter struct {
Proxy
}
func NewCounter(key string, opts ...ProxyOption) (*Counter, error) {
proxy, err := NewProxy(key, opts...)
if err != nil {
return nil, err
}
return &Counter{Proxy: *proxy}, nil
}
func NewCounterWithDefault(key string, defaultValue int64, opts ...ProxyOption) (c *Counter, err error) {
proxy, err := NewProxy(key, opts...)
if err != nil {
return
}
c = &Counter{Proxy: *proxy}
err = proxy.watch(func() error {
_, err := c.Increment(defaultValue)
return err
})
return
}
func (c *Counter) Increment(by int64) (int64, error) {
pipe := c.client.TxPipeline()
if c.expiresIn > 0 {
pipe.SetNX(c.ctx, c.key, 0, c.expiresIn)
}
incr := pipe.IncrBy(c.ctx, c.key, by)
_, err := pipe.Exec(c.ctx)
if err != nil {
return 0, err
}
return incr.Val(), nil
}
func (c *Counter) Decrement(by int64) (int64, error) {
pipe := c.client.TxPipeline()
if c.expiresIn > 0 {
pipe.SetNX(c.ctx, c.key, 0, c.expiresIn)
}
decr := pipe.DecrBy(c.ctx, c.key, by)
_, err := pipe.Exec(c.ctx)
if err != nil {
return 0, err
}
return decr.Val(), nil
}
// An empty value returned when there is a Redis error as a failsafe
func (c *Counter) Value() (v int64) {
v, err := c.client.Get(c.ctx, c.key).Int64()
if err != nil && err != redis.Nil {
if debugLogger != nil {
debugLogger.Warn("Counter#Value", err)
}
}
return
}
func (c *Counter) ValueResult() (int64, error) {
return c.client.Get(c.ctx, c.key).Int64()
}
func (c *Counter) Reset() (err error) {
_, err = c.client.Del(c.ctx, c.key).Result()
return
}