npm install redis
Operating System: Ubuntu 24.04.3 LTS / x86_64
Runtime Version: GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)
npm install ioredis
Operating System: Ubuntu 24.04.3 LTS / x86_64
Runtime Version: GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)
Instance ID:Password format, while custom accounts use the Username@Password format. Instances with password-free authentication do not require a password.const { createClient } = require('redis');async function main() {// Create a client connection.const client = createClient({url: 'redis://192.xx.xx.2:6379', // Instance VIP addresspassword: 'crs-xxxx:password', // Default account password format: Instance ID:Passwordsocket: {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 handlingclient.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 operationsawait client.hSet('user:1001', { name: 'Zhang San', age: '28' });const userInfo = await client.hGetAll('user:1001');console.log('user info:', userInfo);// List operationsawait 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);
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);
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 addressport: 6379, // Instance portpassword: 'crs-xxxx:password', // Default account password format: Instance ID:Passworddb: 0, // Database numberconnectTimeout: 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 requestenableReadyCheck: true, // Connection readiness checklazyConnect: 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 operationsconst 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);
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 certificaterejectUnauthorized: 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);
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 |
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 |
reconnectStrategy is configured correctly.Esta página foi útil?
Você também pode entrar em contato com a Equipe de vendas ou Enviar um tíquete em caso de ajuda.
comentários