go操作redis cluster集群

github.com/go-redis/redis 非常友好的SDK

package redis_cluster

import (
    "fmt"
    "log"
    "strconv"
    "testing"
    "time"

    "github.com/go-redis/redis/v7"
)

var clusterClient *redis.ClusterClient

func init() {
    log.SetFlags(log.Llongfile | log.Lshortfile)
    // 连接redis集群
    clusterClient = redis.NewClusterClient(&redis.ClusterOptions{
        Addrs: []string{ // 填写master主机
            "192.168.21.22:30001",
            "192.168.21.22:30002",
            "192.168.21.22:30003",
        },
        Password:     "123456",              // 设置密码
        DialTimeout:  50 * time.Microsecond, // 设置连接超时
        ReadTimeout:  50 * time.Microsecond, // 设置读取超时
        WriteTimeout: 50 * time.Microsecond, // 设置写入超时
    })
    // 发送一个ping命令,测试是否通
    s := clusterClient.Do("ping").String()
    fmt.Println(s)
}

func TestConnByRedisCluster(t *testing.T) {
    // 测试一个set功能
    s := clusterClient.Set("name", "barry", time.Second*60).String()
    fmt.Println(s)
}
func TestPipe(t *testing.T) {
    // 测试管道发送多条命令.
    pipe := clusterClient.Pipeline()
    for i := 0; i < 10; i++ {
        pipe.Set("go"+strconv.Itoa(i), strconv.Itoa(i), time.Second*300)
    }
    // 真正执行发送操作.
    result, err := pipe.Exec()
    if err != nil {
        t.Error(err)
    }
    t.Log(result)
}

// 验证上面是否拿到数据
func TestGetKey(t *testing.T) {
    for i := 0; i < 10; i++ {
        ret := clusterClient.Get("go" + strconv.Itoa(i)).String()
        fmt.Println(ret)
    }
}

你可能感兴趣的:(go操作redis cluster集群)