tencent cloud

Tencent Cloud Distributed Cache (Redis OSS-Compatible)

Node.JS Connection Sample

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

Preparations

Environment Requirement

Node.js 14 or later.
npm or yarn package manager.

Installing a client

Use npm to install the node-redis client (version 4.x or later recommended):
npm 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)

Or use the ioredis client:
npm install ioredis

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 of the instance (6379 by default).
4. In the Configuration Information section, obtain the connection password of the instance.
Default accounts use the Instance ID:Password format, while custom accounts use the Username@Password format. Instances with password-free authentication do not require a password.

Connection Example

In proxy mode, clients connect to an instance 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.

Basic Connection Example for node-redis

const { createClient } = require('redis');

async function main() {
// Create a client connection.
const client = createClient({
url: 'redis://192.xx.xx.2:6379', // Instance VIP address
password: 'crs-xxxx:password', // Default account password format: Instance ID:Password
socket: {
connectTimeout: 2000, // Connection timeout (in milliseconds)
reconnectStrategy: (retries) => {
if (retries > 10) return new Error('Max retries reached');
return Math.min(retries * 200, 3000); // Reconnection backoff policy
}
}
});

// Error handling
client.on('error', (err) => console.error('Redis Client Error:', err));
client.on('connect', () => console.log('Redis connected'));
client.on('reconnecting', () => console.log('Redis reconnecting...'));

// Establish a connection.
await client.connect();

// Write data.
await client.set('name', 'Distributed Cache');

// Read data.
const value = await client.get('name');
console.log('get name:', value);

// Set a Key with an expiration time (EX in seconds).
await client.set('session:user123', 'session_data', { EX: 3600 });

// Hash operations
await client.hSet('user:1001', { name: 'Zhang San', age: '28' });
const userInfo = await client.hGetAll('user:1001');
console.log('user info:', userInfo);

// List operations
await client.lPush('queue:tasks', ['task1', 'task2', 'task3']);
const task = await client.rPop('queue:tasks');
console.log('dequeued task:', task);

// Close the connection.
await client.quit();
}

main().catch(console.error);

Custom Account Connection Example for node-redis

const { createClient } = require('redis');

async function main() {
const client = createClient({
url: 'redis://192.xx.xx.2:6379',
password: 'myuser@MyPassword', // Proxy mode custom account: the entire "username@password" string is passed as the password.
socket: {
connectTimeout: 2000
}
});

client.on('error', (err) => console.error('Redis Client Error:', err));
await client.connect();

await client.set('key', 'value');
console.log(await client.get('key'));

await client.quit();
}

main().catch(console.error);

Connection Example for ioredis

const Redis = require('ioredis');

// Create a connection (ioredis has built-in connection pooling and automatic reconnection).
const redis = new Redis({
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
connectTimeout: 2000, // Connection timeout (milliseconds)
commandTimeout: 2000, // Command timeout (in milliseconds)
retryStrategy: (times) => {
if (times > 10) return null; // Stop reconnecting when the retry limit is exceeded.
return Math.min(times * 200, 3000);
},
maxRetriesPerRequest: 3, // Maximum retry attempts per request
enableReadyCheck: true, // Connection readiness check
lazyConnect: false // Establish the connection immediately.
});

redis.on('connect', () => console.log('Redis connected'));
redis.on('error', (err) => console.error('Redis error:', err));

async function main() {
// Write data.
await redis.set('name', 'Distributed Cache');

// Read data.
const value = await redis.get('name');
console.log('get name:', value);

// Set a Key with an expiration time.
await redis.setex('session:user123', 3600, 'session_data');

// Pipeline batch operations
const pipeline = redis.pipeline();
pipeline.set('key1', 'value1');
pipeline.set('key2', 'value2');
pipeline.set('key3', 'value3');
pipeline.get('key1');
pipeline.get('key2');
pipeline.get('key3');
const results = await pipeline.exec();
console.log('pipeline results:', results);

// Close the connection.
redis.disconnect();
}

main().catch(console.error);

SSL Encryption Connection Example

const { createClient } = require('redis');
const fs = require('fs');

async function main() {
const client = createClient({
url: 'rediss://192.xx.xx.2:6379', // Enable SSL with the rediss:// protocol.
password: 'crs-xxxx:password',
socket: {
connectTimeout: 2000,
tls: true,
ca: fs.readFileSync('/path/to/ca.pem'), // CA certificate
rejectUnauthorized: true
}
});

client.on('error', (err) => console.error('Redis Client Error:', err));
await client.connect();

await client.set('ssl_test', 'encrypted_connection');
console.log(await client.get('ssl_test'));

await client.quit();
}

main().catch(console.error);

Connection Parameter Description

node-redis Parameters

Parameter
Description
Recommended Value
url
Connection address, format: redis://host:port
-
password
Authentication password
Default account format: instance ID:password
socket.connectTimeout
Connection timeout (ms)
2000
socket.reconnectStrategy
Reconnection backoff policy
Exponential backoff with an upper limit of 3000 ms
maxCommandRedirections
Maximum number of redirections (Cluster mode)
3

ioredis Parameters

Parameter
Description
Recommended Value
host
Instance connection address
-
port
Instance port number
6379
password
Authentication password
Default account format: instance ID:password
connectTimeout
Connection timeout (ms)
2000
commandTimeout
Command timeout (ms)
2000
maxRetriesPerRequest
Maximum retry attempts per request
3
maxRedirections
Maximum number of redirections (Cluster mode)
3

FAQs

Connection Timeout

Confirm that the CVM hosting the client and the Distributed Cache 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.

No Automatic Reconnection After Connection Interruption

Confirm that reconnectStrategy is configured correctly.
Confirm that the network environment is stable and that the security group rule has not been changed.

Ajuda e Suporte

Esta página foi útil?

comentários