tencent cloud

Tencent Cloud Distributed Cache (Redis OSS-Compatible)

Node.JS Connection Sample

PDF
Modo Foco
Tamanho da Fonte
Última atualização: 2026-03-17 17:45:56

Prerequisites

Run the npm install hiredis redis command to install node-redis.
Note:
Note: Please use the latest version of npm. For details, see npm official documentation.

Example Code

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

/** Fill in the following parameters with your Redis instance's private IP address, port number, instance ID, and password */
const host = "192.xx.xx.2";
const port = "6379";
const instanceid = "c53xx52f-55dc-4c22-a941-630xxx88";
const pwd = "12as6zb";

// Create a Redis client (new version API)
const client = createClient({
// Use URL format with authentication information
url: `redis://${encodeURIComponent(instanceid)}:${encodeURIComponent(pwd)}@${host}:${port}`,
// or use separate parameters (choose either one)
/*
socket: {
host: host,
port: parseInt(port) // Underwrite the port is a number
},
username: instanceid, // Redis 6.0+ ACL username
password: pwd,
*/
// other configuration
pingInterval: 60000, // Keep the connection active
disableOfflineQueue: true // Disable command caching when offline
});

// Redis connection error handling (event name unchanged in new version)
client.on('error', (err) => {
console.error('Redis connection error:', err);
});

// Connect to Redis and execute operations
(async () => {
try {
// Explicitly establish a connection (new version requirement)
await client.connect();
console.log('Redis connected successfully');

/** Start operating the Redis instance */
// Set a Key (new version API)
const setResult = await client.set("redis", "tencent");
console.log(`set key redis ${setResult}, value is tencent`);
// Get Key (new version API)
const value = await client.get("redis");
console.log(`get key redis is: ${value}`);
} catch (err) {
console.error('Redis operation error:', err);
} finally {
// Close client when program ends (new version uses quit or disconnect)
await client.quit(); // or client.disconnect()
console.log('Redis connection closed');
}
})();

Execution Result

Note:
Note: If an exception occurred during connection, please refer to Private Network Unable to Connect Location Guide to fix it.
Redis connected successfully
set key redis OK, value is tencent
get key redis is: tencent
Redis connection closed

Ajuda e Suporte

Esta página foi útil?

comentários