-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathredis.go
70 lines (56 loc) · 1.23 KB
/
redis.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
package redis
import (
"time"
redigo "github.com/gomodule/redigo/redis"
)
// Pool contains Redis pool
var Pool *redigo.Pool
// NewPool initialises a new Redis pool
func NewPool(endpoint string, maxIdle int, idleTimeout time.Duration) *redigo.Pool {
return &redigo.Pool{
MaxIdle: maxIdle,
IdleTimeout: idleTimeout * time.Second,
Dial: func() (redigo.Conn, error) {
c, err := redigo.DialURL(endpoint)
if err != nil {
return nil, err
}
return c, err
},
}
}
// Store stores key-value pairs in Redis with expiry
func Store(key string, value interface{}, expiryInSeconds int) error {
conn := Pool.Get()
conn.Send("MULTI")
conn.Send("SET", key, value)
if expiryInSeconds > 0 {
conn.Send("EXPIRE", key, expiryInSeconds)
}
_, err := conn.Do("EXEC")
if err != nil {
return err
}
return nil
}
// Retrieve retrieves value by key
func Retrieve(key string) (interface{}, error) {
conn := Pool.Get()
reply, err := conn.Do("GET", key)
if err != nil {
if err == redigo.ErrNil {
return reply, nil
}
return reply, err
}
return reply, err
}
// Delete deletes a value by key
func Delete(key string) error {
conn := Pool.Get()
_, err := conn.Do("DEL", key)
if err != nil {
return err
}
return nil
}