đ Redis Cache Check Explained
Understand how Upstash Redis checks and returns cached items in serverless functions…
đģ Numbered Code Block
1. import { Redis } from "@upstash/redis"; 2. const redis = Redis.fromEnv(); 3. 4. const cacheKey = `item:${itemId}`; 5. 6. // Check cache 7. const cachedItem = await redis.get(cacheKey); 8. if (cachedItem) { 9. console.log("Cache hit"); 10. return JSON.parse(cachedItem); 11. } đ§ What This Code Does
- Lines 1–2: Import and initialize the Redis client using environment variables.
- Line 4: Construct a unique cache key using the item ID.
- Lines 6–7: Attempt to retrieve the cached value from Redis.
- Lines 8–11: If a cached value exists, log a cache hit and return the parsed object.
✅ This logic helps reduce redundant API/database calls and speeds up response time using Redis.
đ Glossary (Kid-Friendly)
| Term | Meaning |
|---|---|
Redis | A fast memory tool that stores and retrieves data quickly |
Cache | Temporary storage that remembers things for faster access |
Environment Variables | Secret settings used to connect to services safely |
Key | A label used to find stored data |
JSON.parse | Turns a saved text into usable data |
Cache Hit | Means the data was found in the cache |
No comments:
Post a Comment