-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredisconn.go
74 lines (64 loc) · 1.62 KB
/
redisconn.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
package redisconn
import (
"fmt"
"os"
"github.com/go-redis/redis"
"github.com/sivaosorg/govm/dbx"
"github.com/sivaosorg/govm/logger"
"github.com/sivaosorg/govm/redisx"
"github.com/sivaosorg/govm/utils"
)
var (
_logger = logger.NewLogger()
)
func NewRedis() *Redis {
return &Redis{}
}
func (r *Redis) SetConn(value *redis.Client) *Redis {
r.conn = value
return r
}
func (r *Redis) SetConfig(value redisx.RedisConfig) *Redis {
r.Config = value
return r
}
func (r *Redis) SetState(value dbx.Dbx) *Redis {
r.State = value
return r
}
func (r *Redis) Json() string {
return utils.ToJson(r)
}
func (r *Redis) GetConn() *redis.Client {
return r.conn
}
func NewClient(config redisx.RedisConfig) (*Redis, dbx.Dbx) {
instance := NewRedis()
s := dbx.NewDbx().SetDatabase(config.Database)
if !config.IsEnabled {
s.SetConnected(false).
SetMessage("Redis unavailable").
SetError(fmt.Errorf(s.Message))
instance.SetState(*s)
return instance, *s
}
client := redis.NewClient(&redis.Options{
Addr: config.UrlConn,
Password: config.Password,
DialTimeout: config.Timeout,
DB: 0,
})
err := client.Ping().Err()
if err != nil {
s.SetConnected(false).SetError(err).SetMessage(err.Error())
instance.SetState(*s)
return instance, *s
}
if config.DebugMode {
_logger.Info(fmt.Sprintf("Redis client connection:: %s", config.Json()))
_logger.Info(fmt.Sprintf("Connected successfully to redis cache:: %s/%s", config.UrlConn, config.Database))
}
s.SetConnected(true).SetMessage("Connected successfully").SetPid(os.Getpid()).SetNewInstance(true)
instance.SetConn(client).SetState(*s)
return instance, *s
}