proxy.go 1.2 KB
Newer Older
Y
Your Name 已提交
1
package redismanager
E
eoLinker API Management 已提交
2 3

import (
黄孟柱 已提交
4
	"github.com/go-redis/redis"
E
eoLinker API Management 已提交
5 6 7 8 9 10 11 12 13
)

type redisProxy struct {
	redis.Cmdable
	config RedisConfig
}

func (p *redisProxy) Nodes() []string {

Y
Your Name 已提交
14
	ch := make(chan string, 1)
E
eoLinker API Management 已提交
15 16 17 18
	switch p.config.GetMode() {
	case RedisModeCluster:
		{
			conn := p.Cmdable.(*redis.ClusterClient)
Y
Your Name 已提交
19
			go func(ch chan string) {
E
eoLinker API Management 已提交
20
				conn.ForEachMaster(func(client *redis.Client) error {
Y
Your Name 已提交
21
					ch <- client.Options().Addr
E
eoLinker API Management 已提交
22 23 24 25 26 27 28 29 30 31 32
					return nil
				})
				close(ch)
			}(ch)

		}

	case RedisModeStand:
		{

			conn := p.Cmdable.(*redis.Ring)
Y
Your Name 已提交
33
			go func(ch chan string) {
E
eoLinker API Management 已提交
34
				conn.ForEachShard(func(client *redis.Client) error {
Y
Your Name 已提交
35
					ch <- client.Options().Addr
E
eoLinker API Management 已提交
36 37 38 39 40 41 42
					return nil
				})
				close(ch)
			}(ch)
		}
	}

Y
Your Name 已提交
43 44 45
	nodes := make([]string, 0, 10)
	for addr := range ch {
		nodes = append(nodes, addr)
E
eoLinker API Management 已提交
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
	}
	return nodes
}

func (p *redisProxy) Foreach(fn func(client *redis.Client) error) error {
	switch p.config.GetMode() {
	case RedisModeCluster:
		{
			conn := p.Cmdable.(*redis.ClusterClient)
			return conn.ForEachMaster(fn)
		}

	case RedisModeStand:
		{

			conn := p.Cmdable.(*redis.Ring)
			return conn.ForEachShard(fn)
		}
	}

	panic("未知错误")

}

func (p *redisProxy) GetConfig() RedisConfig {
	return p.config
}