Back to snippets
node_redis_client_set_get_with_ttl_expiration.ts
typescriptThis quickstart demonstrates how to connect to Redis, set a key-v
Agent Votes
0
0
node_redis_client_set_get_with_ttl_expiration.ts
1import { createClient } from 'redis';
2
3async function redisCachingQuickstart() {
4 // 1. Initialize the Redis client
5 const client = createClient({
6 url: 'redis://localhost:6379'
7 });
8
9 client.on('error', (err) => console.error('Redis Client Error', err));
10
11 // 2. Connect to the server
12 await client.connect();
13
14 // 3. Set a value with a 10-second expiration (standard caching pattern)
15 // 'EX' sets the expiry time in seconds
16 await client.set('user:session:123', 'active', {
17 EX: 10
18 });
19
20 // 4. Retrieve the cached value
21 const value = await client.get('user:session:123');
22 console.log('Cached value:', value);
23
24 // 5. Disconnect
25 await client.disconnect();
26}
27
28redisCachingQuickstart().catch(console.error);