redis_conn.go 1.8 KB
Newer Older
Y
Your Name 已提交
1
package redis_manager
E
eoLinker API Management 已提交
2 3

import (
Y
Your Name 已提交
4 5 6
	"fmt"
	"sort"
	"strings"
E
eoLinker API Management 已提交
7
	"sync"
Y
Your Name 已提交
8 9

	"github.com/go-redis/redis"
E
eoLinker API Management 已提交
10 11 12 13 14 15 16 17
)

var (
	def           Redis
	defaultConfig RedisConfig
	defLocker     sync.Locker
)

Y
Your Name 已提交
18
//SetDefault 设置默认redis
E
eoLinker API Management 已提交
19 20 21 22
func SetDefault(r Redis) {
	def = r
}

Y
Your Name 已提交
23
//GetConnection 获取redis连接
E
eoLinker API Management 已提交
24
func GetConnection() Redis {
Y
Your Name 已提交
25 26 27 28 29 30 31 32 33
	//if def != nil {
	return def
	//}
	//defLocker.Lock()
	//defer defLocker.Unlock()
	//
	//def = Create(defaultConfig)
	//return def
}
E
eoLinker API Management 已提交
34

Y
Your Name 已提交
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
//CheckConnection 获取redis连接
func CheckConnection(mode, addrs, password, masters string, dbIndex int) bool {
	switch mode {
	case RedisModeCluster:
		{
			a := strings.Split(addrs, ",")
			option := &redis.ClusterOptions{
				Addrs:          a,
				Password:       password,
				PoolSize:       2000,
				ReadOnly:       true,
				RouteByLatency: true,
			}
			r := redis.NewClusterClient(option)
			defer r.Close()
			if _, err := r.Ping().Result(); err != nil {
				return false
			}
			return true
		}
	case RedisModeSentinel:
		{
			a := strings.Split(addrs, ",")
			option := redis.FailoverOptions{
				SentinelAddrs: a,
				MasterName:    masters,
				Password:      password,
				DB:            dbIndex,
				PoolSize:      _PoolSize,
			}
			r := redis.NewFailoverClient(&option)
			defer r.Close()
			if _, err := r.Ping().Result(); err != nil {
				return false
			}
			return true
		}
	case RedisModeStand:
		{
E
eoLinker API Management 已提交
74

Y
Your Name 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
			a := strings.Split(addrs, ",")

			option := redis.RingOptions{
				Addrs:    make(map[string]string),
				Password: password,
				DB:       dbIndex,

				PoolSize: _PoolSize,
			}
			sort.Strings(a)
			for i, ad := range a {
				option.Addrs[fmt.Sprintf("shad:%d", i)] = ad
			}
			r := redis.NewRing(&option)
			defer r.Close()
			if _, err := r.Ping().Result(); err != nil {
				return false
			}
			return true
		}
E
eoLinker API Management 已提交
95
	}
Y
Your Name 已提交
96
	return false
E
eoLinker API Management 已提交
97 98

}