tencent cloud

Tencent Cloud Distributed Cache (Redis OSS-Compatible)

Python Connection Sample

ダウンロード
フォーカスモード
フォントサイズ
最終更新日: 2026-09-07 14:31:33
AI翻訳
This document provides an example of using a Python client to connect to a Tencent Cloud Distributed Cache instance.

Prerequisites

Environment Requirement

Python 3.7 or later.
pip package manager.

Installing a client

pip install redis

Running Environment

Operating System: Ubuntu 24.04.3 LTS / x86_64

Runtime Version: GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)

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 (default is 6379).
4. In the Configuration Information section, obtain the connection password for the instance.
Default accounts use the Instance ID:Password format, custom accounts use the Username@Password format, and 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 be aware of backend topology changes.

Connection Pool Example (Recommended)

import redis

# Create a connection pool
pool = redis.ConnectionPool(
host='192.xx.xx.2', # Instance VIP address
port=6379, # Instance port
password='crs-xxxx:password', # Default account password format: Instance ID:Password
db=0, # Database number
max_connections=200, # Maximum number of connections
socket_connect_timeout=2, # Connection timeout (in seconds)
socket_timeout=2, # Read/write timeout (in seconds)
decode_responses=True, # Automatically decode as strings
health_check_interval=30 # Health check interval (in seconds)
)

# Create a Redis client
r = redis.Redis(connection_pool=pool)

# Write data.
r.set('name', 'Distributed Cache')

# Read data.
value = r.get('name')
print(f'get name: {value}')

# Set a Key with an expiration time
r.setex('session:user123', 3600, 'session_data')

# Hash operations
r.hset('user:1001', mapping={'name': 'Zhang San', 'age': '28'})
user_info = r.hgetall('user:1001')
print(f'user info: {user_info}')

# List operations
r.lpush('queue:tasks', 'task1', 'task2', 'task3')
task = r.rpop('queue:tasks')
print(f'dequeued task: {task}')

# Pipeline batch operations
pipe = r.pipeline()
pipe.set('key1', 'value1')
pipe.set('key2', 'value2')
pipe.set('key3', 'value3')
pipe.get('key1')
pipe.get('key2')
pipe.get('key3')
results = pipe.execute()
print(f'pipeline results: {results}')

Custom Account Connection Example

import redis

# Custom account password format: username@password
pool = redis.ConnectionPool(
host='192.xx.xx.2',
port=6379,
password='myuser@MyPassword', # Proxy mode custom account: the entire "username@password" string is passed as the password.
db=0,
max_connections=200,
socket_connect_timeout=2,
socket_timeout=2,
decode_responses=True
)

r = redis.Redis(connection_pool=pool)
r.set('key', 'value')
print(r.get('key'))

SSL Encryption Connection Example

import redis

# SSL Encryption Connection
pool = redis.ConnectionPool(
host='192.xx.xx.2',
port=6379,
password='crs-xxxx:password',
db=0,
max_connections=200,
socket_connect_timeout=2,
socket_timeout=2,
decode_responses=True,
ssl=True, # Enable SSL.
ssl_ca_certs='/path/to/ca.pem', # Path to the CA certificate
ssl_cert_reqs='required' # Verify the server certificate.
)

r = redis.Redis(connection_pool=pool)
r.set('ssl_test', 'encrypted_connection')
print(r.get('ssl_test'))

Asynchronous Connection Example (asyncio)

import asyncio
import redis.asyncio as aioredis

async def main():
# Create an asynchronous connection pool
pool = aioredis.ConnectionPool(
host='192.xx.xx.2',
port=6379,
password='crs-xxxx:password',
db=0,
max_connections=200,
socket_connect_timeout=2,
socket_timeout=2,
decode_responses=True
)

r = aioredis.Redis(connection_pool=pool)

# Asynchronous write
await r.set('async_key', 'async_value')

# Asynchronous read
value = await r.get('async_key')
print(f'async get: {value}')

# Asynchronous Pipeline
pipe = r.pipeline()
pipe.set('key1', 'value1')
pipe.set('key2', 'value2')
pipe.get('key1')
pipe.get('key2')
results = await pipe.execute()
print(f'async pipeline: {results}')

# Close the connection.
await r.aclose()
await pool.aclose()

asyncio.run(main())

Connection Parameter Description

Parameter
Description
Recommended Value
host
Instance connection address.
-
port
Instance port number
6379
password
Authentication password
Default account format: Instance ID:Password
max_connections
Maximum Number of Connections
200
socket_connect_timeout
Connection timeout (s)
2
socket_timeout
Read/write timeout (s)
2
health_check_interval
Health check interval (s)
30
decode_responses
Automatically decode responses into strings
True
retry_on_timeout
Automatic retry on timeout
True

FAQs

Connection Timeout

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

Connection Pool Exhaustion

Check whether max_connections is set appropriately.
Confirm that the application code has no connection leaks (connections not released properly).
Consider increasing the connection pool size or optimizing the concurrency model of your application.

ヘルプとサポート

この記事はお役に立ちましたか?

フィードバック