/
redigo.go
78 lines (65 loc) · 1.53 KB
/
redigo.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
package redigo
import (
"context"
"errors"
"github.com/albertwidi/go-project-example/internal/pkg/redis"
redigo "github.com/gomodule/redigo/redis"
)
// Redigo redis
type Redigo struct {
pool *redigo.Pool
}
// Config of connection
type Config struct {
MaxActive int
MaxIdle int
Timeout int
}
// New redis connection using redigo library
func New(ctx context.Context, address string, config *Config) (*Redigo, error) {
pool := &redigo.Pool{
Dial: func() (redigo.Conn, error) {
return redigo.Dial("tcp", address)
},
}
r := Redigo{
pool: pool,
}
return &r, nil
}
// getConn return the connection of redigo
func (rdg *Redigo) getConn(ctx context.Context) (redigo.Conn, error) {
return rdg.pool.GetContext(ctx)
}
func (rdg *Redigo) do(ctx context.Context, cmd string, args ...interface{}) (interface{}, error) {
conn, err := rdg.getConn(ctx)
if err != nil {
return nil, err
}
defer conn.Close()
resp, err := conn.Do(cmd, args...)
return resp, err
}
// Ping the redis
func (rdg *Redigo) Ping(ctx context.Context) (string, error) {
val, err := rdg.do(ctx, redis.CommandPing)
return redigo.String(val, err)
}
// Close all redis connection
func (rdg *Redigo) Close() error {
return rdg.pool.Close()
}
// IsErrNil return true if error is nil
func (rdg *Redigo) IsErrNil(err error) bool {
if !errors.Is(err, redigo.ErrNil) {
return false
}
return true
}
// IsResponseOK return true if result value of command is ok
func (rdg *Redigo) IsResponseOK(result string) bool {
if result != "OK" {
return false
}
return true
}