KING 博主等级

一帆风顺 ⛵️⛵️⛵️

Go

golang 连接redis哨兵模式

钟晓川
2024-10-14 / 0 点赞 / 29 阅读

安装依赖包

go get -u github.com/go-redis/redis/v9

代码

import (
	"context"
	"github.com/redis/go-redis/v9"
	"log"
	"testing"
)

func initSentinel() *redis.Client {
	rdb := redis.NewFailoverClient(&redis.FailoverOptions{
		MasterName:    "mymaster",
		SentinelAddrs: []string{"192.168.98.138:26380", "192.168.98.138:26381", "192.168.98.138:26382"},
		Password:      "szz123",
	})

	// 设置上下文
	ctx := context.Background()

	// 测试连接
	_, err := rdb.Ping(ctx).Result()
	if err != nil {
		log.Fatalf("Failed to connect to Redis: %v", err)
	}
	return rdb
}

func TestSet(t *testing.T) {
	var client = initSentinel()

	ctx := context.Background()
	client.Set(ctx, "name", "王五", 0)

	rs := client.Get(ctx, "name")
	t.Log(rs.Val())
}
0