package fcredis import ( "context" "errors" "fmt" goRedis "github.com/go-redis/redis/v8" "strings" ) const ( ModeSingle = "single" ModeSentinel = "sentinel" ModeCluster = "cluster" ) const ( SentinelClusterMode = "sentinelCluster" SentinelNormalMode = "sentinelNormal" ) var ( gUniClient goRedis.UniversalClient gMode string gSentinelMode string ) var ( addrLackErr = errors.New("client init addr empty") ) // Init 用来初始化redis,mode--redis模式,可选项为: single--单例,sentinel--主从,cluster--集群 // opt是对应初始化的配置,需要根据mode采用相应的类型: single:go-redis.Options,sentinel:go-redis.FailoverOptions,cluster:go-redis.ClusterOptions // ext参数用来为主从模式指定是否采用"主节点写从节点读"的读写策略(默认采用)。不采用该策略时ext参数填为: fcredis.SentinelNormalMode func Init(mode string, opt interface{}, ext ...interface{}) error { gMode = mode var err error defer func(err error) { fmt.Printf("[fcredis] mode:[%s],opt:%+v,ext:%+v,err:%+v\n", mode, opt, ext, err) }(err) switch strings.ToLower(mode) { case ModeSingle: option, ok := opt.(*goRedis.Options) if !ok { return errors.New("redis single mode need opt: go-redis.Options") } err = initSingleClient(option) case ModeSentinel: gSentinelMode = SentinelClusterMode option, ok := opt.(*goRedis.FailoverOptions) if !ok { return errors.New("redis sentinel mode need opt: goRedis.FailoverOptions") } if len(ext) != 0 { if sentinelMode, ok := ext[0].(string); ok { if sentinelMode == SentinelNormalMode { gSentinelMode = SentinelNormalMode err = initSentinelFailoverClient(option) break } } } fmt.Printf("[fcredis] sentinel mode:%s\n", gSentinelMode) err = initSentinelFailoverClusterClient(option) case ModeCluster: option, ok := opt.(*goRedis.ClusterOptions) if !ok { return errors.New("redis cluster mode need opt: go-redis.ClusterOptions") } err = initClusterClient(option) default: return errors.New("mode must be: single、sentinel or cluster ") } return err } func initSingleClient(opt *goRedis.Options) (err error) { fmt.Println("[fcredis] initSingleClient.") if opt.Addr == "" { return addrLackErr } gUniClient = goRedis.NewClient(opt) return nil } func initSentinelFailoverClient(opt *goRedis.FailoverOptions) (err error) { fmt.Println("[fcredis] initSentinelFailoverClient.") if len(opt.SentinelAddrs) == 0 { return addrLackErr } gUniClient = goRedis.NewFailoverClient(opt) _, err = gUniClient.Ping(context.Background()).Result() if err != nil { return err } return nil } func initSentinelFailoverClusterClient(opt *goRedis.FailoverOptions) (err error) { fmt.Println("[fcredis] initSentinelFailoverClusterClient.") if len(opt.SentinelAddrs) == 0 { return addrLackErr } gUniClient = goRedis.NewFailoverClusterClient(opt) _, err = gUniClient.Ping(context.Background()).Result() if err != nil { return err } return nil } func initClusterClient(opt *goRedis.ClusterOptions) (err error) { fmt.Println("[fcredis] initClusterClient.") if len(opt.Addrs) == 0 { return addrLackErr } gUniClient = goRedis.NewClusterClient(opt) _, err = gUniClient.Ping(context.Background()).Result() if err != nil { return err } return nil }