tencent cloud

Tencent Cloud Distributed Cache (Redis OSS-Compatible)

Go Connection Sample

Baixar
Modo Foco
Tamanho da Fonte
Última atualização: 2026-09-07 14:31:33
Traduzido por IA
This document provides an example of using a Go client to connect to a Distributed Cache instance.

Preparations

Environment Requirement

Go 1.18 or later.
Go Modules package management.

Installing a client

We recommend using the go-redis client (v9 or later):
go get github.com/redis/go-redis/v9

Obtaining Connection Information

1. Log in to the Distributed Cache console.
2. In the instance list, click the target instance ID to go to the instance details page.
3. In the Network Information section, obtain the VIP address and port of the instance (default: 6379).
4. In the Configuration Information section, obtain the connection password for the instance.
For default accounts, use the Instance ID:Password format. For custom accounts, use the Username@Password format. Password-free authentication instances do not require a password.

Connection Example

In proxy mode, clients connect to instances through the unified VIP address provided by the proxy layer. The proxy automatically handles request routing and failover, so clients do not need to perceive backend topology changes.

Connection Pool Example (Recommended)

package main

import (
"context"
"fmt"
"time"

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

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

// Create a Redis client
rdb := redis.NewClient(&redis.Options{
Addr: "192.xx.xx.2:6379", // Instance VIP address
Password: "crs-xxxx:password", // Default account password format: Instance ID:Password
DB: 0, // Database number
PoolSize: 200, // Connection pool size
MinIdleConns: 50, // Minimum number of idle connections
MaxIdleConns: 200, // Maximum number of idle connections
DialTimeout: 2 * time.Second, // Connection timeout
ReadTimeout: 2 * time.Second, // Read timeout
WriteTimeout: 2 * time.Second, // Write timeout
PoolTimeout: 3 * time.Second, // Connection pool acquisition timeout
ConnMaxIdleTime: 30 * time.Minute, // Maximum idle connection lifetime
})

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

// Write data.
err = rdb.Set(ctx, "name", "Distributed Cache", 0).Err()
if err != nil {
panic(err)
}

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

// Set a Key with an expiration time.
err = rdb.Set(ctx, "session:user123", "session_data", 3600*time.Second).Err()
if err != nil {
panic(err)
}

// Hash operations.
err = rdb.HSet(ctx, "user:1001", map[string]interface{}{
"name": "Zhang San",
"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)

// List operations.
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 batch operations.
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)
}

// Close the connection.
rdb.Close()
}

Custom Account Connection Example

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", // Proxy mode custom account: pass the entire "username@password" string as the password.
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 Encryption Connection Example

package main

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

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

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

// Load the CA certificate.
caCert, err := os.ReadFile("/path/to/ca.pem")
if err != nil {
panic(err)
}

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

// Configure TLS.
tlsConfig := &tls.Config{
RootCAs: caCertPool,
InsecureSkipVerify: false, // Verify the server certificate.
}

rdb := redis.NewClient(&redis.Options{
Addr: "192.xx.xx.2:6379",
Password: "crs-xxxx:password",
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()
}

Connection Parameter Description

Parameter
Description
Recommended Value
Addr
Instance connection address.
-
Password
Authentication password
Default account format: Instance ID:Password
PoolSize
Connection pool size (the number of connections per node in Cluster mode)
200
MinIdleConns
Minimum number of free connections.
50
DialTimeout
Connection timeout
2 seconds
ReadTimeout
Read timeout
2 seconds
WriteTimeout
Write timeout
2 seconds
PoolTimeout
Connection pool acquisition timeout
3 seconds
MaxRedirects
Maximum number of redirects (Cluster mode)
3

FAQs

Connection Timeout

Verify that the CVM hosting the client and the distributed cache database instance are in the same VPC.
Verify that the security group rule allows access to the corresponding port.
Verify that the connection address and port are correct.

Connection Pool Exhaustion

Check whether PoolSize is set appropriately.
Verify that PoolTimeout is set appropriately to avoid prolonged blocking.
Check whether the application code has connection leaks (connections not closed properly).

Ajuda e Suporte

Esta página foi útil?

comentários