/
redis.go
45 lines (36 loc) · 980 Bytes
/
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
package db
import (
"fmt"
"github.com/go-redis/redis"
"github.com/realjf/goframe/config"
"github.com/realjf/goframe/exception"
"github.com/realjf/goframe/middleware"
"github.com/realjf/goframe/utils"
)
var RedisClient *redis.Client
type RedisDriver struct {
Host string
Port string
}
func NewRedis(config config.IConfig) *RedisDriver {
configData := config.GetConfigData()
return &RedisDriver{
Host: configData.Redis.Host,
Port: utils.ToString(configData.Redis.Port),
}
}
func (r *RedisDriver) Init() {
if r.Host == "" || r.Port == "" {
exception.CheckError(exception.NewError("redis config is error"), 4001)
}
RedisClient = redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%s", r.Host, r.Port),
Password: "", // no password set
DB: 0, // use default DB
})
_, err := RedisClient.Ping().Result()
if err != nil {
exception.CheckError(exception.NewError(err.Error()), 4002)
}
middleware.Logger.Logger.Info("init redis...")
}