-
Notifications
You must be signed in to change notification settings - Fork 2
/
counters.go
53 lines (41 loc) · 858 Bytes
/
counters.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
package redis
import (
"fmt"
"github.com/go-redis/redis"
)
type Counters struct {
db *Database
key string
}
func (counters *Counters) Key(key string) *Counter {
return &Counter{
db: counters.db,
key: fmt.Sprintf("%s:%s", counters.key, key),
}
}
type Counter struct {
db *Database
key string
}
func (c *Counter) Set(value int64) error {
return c.db.sess.Set(c.key, value, 0).Err()
}
func (c *Counter) Get() (int64, error) {
result, err := c.db.sess.Get(c.key).Int64()
if err != nil {
if err == redis.Nil {
return 0, nil
}
return 0, err
}
return result, nil
}
func (c *Counter) Increment() (int64, error) {
return c.IncrementBy(1)
}
func (c *Counter) Decrement() (int64, error) {
return c.IncrementBy(-1)
}
func (c *Counter) IncrementBy(value int64) (int64, error) {
return c.db.sess.IncrBy(c.key, value).Result()
}