如何使用go-redis SDK将本地Golang代码连接至Amazon Elastic Redis集群
使用go-redis SDK连接Amazon ElastiCache Redis集群
前置准备
- 安装go-redis SDK:执行
go get github.com/redis/go-redis/v9 - 确认ElastiCache集群信息:获取节点端点、端口、认证密码(若启用),并确保本地网络可访问集群(通过VPC VPN、端口转发等方式,同时配置安全组允许本地IP访问)
情况1:非集群模式(Cluster Mode Disabled)
如果你的ElastiCache是主从架构且未开启集群模式,使用普通客户端连接:
package main import ( "context" "fmt" "github.com/redis/go-redis/v9" ) func main() { ctx := context.Background() // 初始化客户端 client := redis.NewClient(&redis.Options{ Addr: "your-primary-endpoint:6379", // 替换为集群主节点端点 Password: "your-auth-password", // 无密码则留空 DB: 0, // 默认数据库 }) // 测试连接 pong, err := client.Ping(ctx).Result() if err != nil { panic(err) } fmt.Println("连接成功:", pong) }
读写分离配置
如果需要利用从节点做读请求,使用NewFailoverClient:
client := redis.NewFailoverClient(&redis.FailoverOptions{ MasterName: "your-master-name", // 控制台可查看主节点名称 SentinelAddrs: []string{"sentinel-1:26379", "sentinel-2:26379"}, // 哨兵节点端点 Password: "your-auth-password", })
情况2:集群模式(Cluster Mode Enabled)
开启集群模式的ElastiCache需要使用集群客户端:
package main import ( "context" "fmt" "github.com/redis/go-redis/v9" ) func main() { ctx := context.Background() // 初始化集群客户端 client := redis.NewClusterClient(&redis.ClusterOptions{ Addrs: []string{"cluster-node-1:6379", "cluster-node-2:6379"}, // 填写部分集群节点端点,客户端会自动发现其余节点 Password: "your-auth-password", // 无密码则留空 }) // 测试连接 pong, err := client.Ping(ctx).Result() if err != nil { panic(err) } fmt.Println("连接成功:", pong) }
关键注意事项
- 网络访问:ElastiCache默认仅限VPC内部访问,本地需通过VPN连接VPC、EC2端口转发等方式打通网络,同时安全组要开放对应端口给本地IP
- 密码认证:若集群启用了Redis AUTH,必须在配置中填写
Password字段 - 版本兼容:确保go-redis v9与ElastiCache的Redis版本兼容,避免出现协议不匹配问题
内容的提问来源于stack exchange,提问作者Mehul Gohil
相关产品推荐
相关产品推荐

