其他分享
首页 > 其他分享> > golang 简单操作 reids-sentinel 代码

golang 简单操作 reids-sentinel 代码

作者:互联网

golang 简单操作 reids-sentinel 代码

`
package main

import (
"flag"
"fmt"
"github.com/go-redis/redis"
"os"
"strings"
"time"
)

var (
//mastername = flag.String("m", "mymaster", "mymaster")
mastername = flag.String("m", "", "mymaster")
//password = flag.String("p", "123456", "password")
password = flag.String("p", "", "password")
//addr = flag.String("a", "172.23.0.105:26379,172.23.0.106:26379,172.23.0.107:26379", "addr:port")
addr = flag.String("a", "", "addr:port")
db = flag.Int("db", 0, "db")
getK = flag.String("get", "", "key")
setKV = flag.String("set", "", "key,value")
delK = flag.String("del", "", "key")
redisCli *redis.Client
timeStr = time.Now().Format("2006-01-02 15:04:05")
)

type RedisSentinelInfo struct {
MasterName string
SentinelAddrs []string
Password string
DB int
}

func NewRedisSentinelInfo(mastername, password string, addr []string, db int) *RedisSentinelInfo {
return &RedisSentinelInfo{
MasterName: mastername,
SentinelAddrs: addr,
Password: password,
DB: db,
}
}

func (r *RedisSentinelInfo) initClient() (err error) {
redisCli = redis.NewFailoverClient(&redis.FailoverOptions{
MasterName: r.MasterName,
SentinelAddrs: r.SentinelAddrs,
Password: r.Password,
DB: r.DB,
})

_, err = redisCli.Ping().Result()
if err != nil {
	return err
}

return nil

}

func (r *RedisSentinelInfo) get(k string) (err error) {
v, err := redisCli.Get(k).Result()
if err != nil {
fmt.Printf("[%s][ERROR] get %s %sfailed, err: %v\n", timeStr, k, v, err)
return
}
fmt.Printf("[%s][SUCCESSFUL] get key: %s, value: %s\n", timeStr, k, v)
return nil
}

func (r *RedisSentinelInfo) set(kvs []string) (err error) {
k := kvs[0]
v := kvs[1]
err = redisCli.Set(k, v, 0).Err()
if err != nil {
fmt.Printf("[%s][ERROR] set %s failed, err: %v\n", timeStr, k, err)
return
}
r.get(k)
return nil
}

func (r *RedisSentinelInfo) del(k string) (err error) {
n, err := redisCli.Del(k).Result()
if err != nil {
fmt.Printf("[%s][ERROR] del %s failed, err: %v\n", timeStr, k, err)
return
}
fmt.Printf("[%s][SUCCESSFUL] 成功删除 %v 个key: %s\n", timeStr, n, k)
return nil
}

func main() {
flag.Parse()
if len(os.Args) < 2 {
flag.Usage()
return
}
rc := NewRedisSentinelInfo(*mastername, password, strings.Split(addr, ","), *db)
err := rc.initClient()
if err != nil {
fmt.Printf("[%s][ERROR] redis-sentinel connect failed, err: %s\n", timeStr, err)
return
}

for _, v := range os.Args {
	switch v {
	case "-get":
		rc.get(*getK)
	case "-set":
		rc.set(strings.Split(*setKV, ","))
	case "-del":
		rc.del(*delK)
	}
}

}

`

标签:return,String,err,nil,reids,golang,flag,sentinel,string
来源: https://www.cnblogs.com/xiaoqshuo/p/15392891.html