帮你快速理解、总结文档立即下载

Go 连接示例

最近更新时间:2026-08-14 15:52:31
我的收藏
本文介绍使用 Go 客户端连接腾讯云分布式缓存数据库实例的示例。

准备工作

环境要求

Go 1.18及以上版本。
Go Modules 包管理。

安装客户端

推荐使用 go-redis 客户端(v9及以上版本):
go get github.com/redis/go-redis/v9

获取连接信息

2. 在实例列表中,单击目标实例 ID,进入实例详情页。
3. 网络信息区域,获取实例的 VIP 地址端口(默认6379)。
4. 配置信息区域,获取实例的连接密码。
默认账号使用实例 ID:密码 格式,自定义账号使用用户名@密码 格式;免密认证实例无需密码。

连接示例

代理模式下,客户端通过 Proxy 代理层提供的统一 VIP 地址连接实例,Proxy 自动处理请求路由和故障转移,客户端无需感知后端拓扑变化。

连接池示例(推荐)

package main

import (
"context"
"fmt"
"time"

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

func main() {
ctx := context.Background()

// 创建 Redis 客户端
rdb := redis.NewClient(&redis.Options{
Addr: "192.xx.xx.2:6379", // 实例 VIP 地址
Password: "crs-xxxx:密码", // 默认账号密码格式:实例ID:密码
DB: 0, // 数据库编号
PoolSize: 200, // 连接池大小
MinIdleConns: 50, // 最小空闲连接数
MaxIdleConns: 200, // 最大空闲连接数
DialTimeout: 2 * time.Second, // 连接超时
ReadTimeout: 2 * time.Second, // 读取超时
WriteTimeout: 2 * time.Second, // 写入超时
PoolTimeout: 3 * time.Second, // 连接池获取超时
ConnMaxIdleTime: 30 * time.Minute, // 空闲连接最大存活时间
})

// 测试连接
pong, err := rdb.Ping(ctx).Result()
if err != nil {
panic(fmt.Sprintf("Redis connection failed: %v", err))
}
fmt.Println("Redis connected:", pong)

// 写入数据
err = rdb.Set(ctx, "name", "腾讯云分布式缓存数据库", 0).Err()
if err != nil {
panic(err)
}

// 读取数据
val, err := rdb.Get(ctx, "name").Result()
if err != nil {
panic(err)
}
fmt.Println("get name:", val)

// 设置带过期时间的 Key
err = rdb.Set(ctx, "session:user123", "session_data", 3600*time.Second).Err()
if err != nil {
panic(err)
}

// 哈希操作
err = rdb.HSet(ctx, "user:1001", map[string]interface{}{
"name": "张三",
"age": "28",
}).Err()
if err != nil {
panic(err)
}

name, err := rdb.HGet(ctx, "user:1001", "name").Result()
if err != nil {
panic(err)
}
fmt.Println("user name:", name)

// 列表操作
err = rdb.LPush(ctx, "queue:tasks", "task1", "task2", "task3").Err()
if err != nil {
panic(err)
}

task, err := rdb.RPop(ctx, "queue:tasks").Result()
if err != nil {
panic(err)
}
fmt.Println("dequeued task:", task)

// Pipeline 批量操作
pipe := rdb.Pipeline()
pipe.Set(ctx, "key1", "value1", 0)
pipe.Set(ctx, "key2", "value2", 0)
pipe.Set(ctx, "key3", "value3", 0)
pipe.Get(ctx, "key1")
pipe.Get(ctx, "key2")
pipe.Get(ctx, "key3")
cmds, err := pipe.Exec(ctx)
if err != nil {
panic(err)
}
for _, cmd := range cmds {
fmt.Printf("pipeline result: %v\\n", cmd)
}

// 关闭连接
rdb.Close()
}

自定义账号连接示例

package main

import (
"context"
"fmt"
"time"

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

func main() {
ctx := context.Background()

rdb := redis.NewClient(&redis.Options{
Addr: "192.xx.xx.2:6379",
Password: "myuser@MyPassword", // 代理模式自定义账号:用户名@密码整体作为密码传入
PoolSize: 200,
MinIdleConns: 50,
DialTimeout: 2 * time.Second,
ReadTimeout: 2 * time.Second,
WriteTimeout: 2 * time.Second,
})

pong, err := rdb.Ping(ctx).Result()
if err != nil {
panic(err)
}
fmt.Println("Redis connected:", pong)

err = rdb.Set(ctx, "key", "value", 0).Err()
if err != nil {
panic(err)
}

val, err := rdb.Get(ctx, "key").Result()
if err != nil {
panic(err)
}
fmt.Println("get key:", val)

rdb.Close()
}

SSL 加密连接示例

package main

import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"os"
"time"

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

func main() {
ctx := context.Background()

// 加载 CA 证书
caCert, err := os.ReadFile("/path/to/ca.pem")
if err != nil {
panic(err)
}

caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)

// 配置 TLS
tlsConfig := &tls.Config{
RootCAs: caCertPool,
InsecureSkipVerify: false, // 验证服务端证书
}

rdb := redis.NewClient(&redis.Options{
Addr: "192.xx.xx.2:6379",
Password: "crs-xxxx:密码",
DB: 0,
PoolSize: 200,
MinIdleConns: 50,
DialTimeout: 2 * time.Second,
ReadTimeout: 2 * time.Second,
WriteTimeout: 2 * time.Second,
TLSConfig: tlsConfig,
})

pong, err := rdb.Ping(ctx).Result()
if err != nil {
panic(err)
}
fmt.Println("SSL Redis connected:", pong)

err = rdb.Set(ctx, "ssl_test", "encrypted_connection", 0).Err()
if err != nil {
panic(err)
}

val, err := rdb.Get(ctx, "ssl_test").Result()
if err != nil {
panic(err)
}
fmt.Println("ssl_test:", val)

rdb.Close()
}

连接参数说明

参数
说明
推荐值
Addr
实例连接地址。
-
Password
认证密码
默认账号格式:实例 ID:密码
PoolSize
连接池大小(Cluster 模式下为每个节点的连接数)
200
MinIdleConns
最小空闲连接数
50
DialTimeout
连接超时
2秒
ReadTimeout
读取超时
2秒
WriteTimeout
写入超时
2秒
PoolTimeout
连接池获取超时
3秒
MaxRedirects
最大重定向次数(Cluster 模式)
3

常见问题

连接超时

确认客户端所在 CVM 与分布式缓存数据库实例在同一 VPC 内。
确认安全组规则已放通对应端口。
确认连接地址和端口正确。

连接池耗尽

检查 PoolSize 是否设置合理。
确认 PoolTimeout 设置合理,避免长时间阻塞。
检查业务代码中是否有连接泄漏(未正确关闭)。