Junior — Middle
Have you used Redis for data caching purposes?
sobes.tech AI
Answer from AI
Yes, Redis is often used for caching data due to its high speed of working with in-memory data. In Node.js, you can use the redis package to interact with the Redis server.
Example of caching a query result:
const redis = require('redis');
const client = redis.createClient();
async function getCachedData(key, fetchFunction) {
return new Promise((resolve, reject) => {
client.get(key, async (err, data) => {
if (err) return reject(err);
if (data) {
return resolve(JSON.parse(data));
} else {
const freshData = await fetchFunction();
client.setex(key, 3600, JSON.stringify(freshData)); // cache for 1 hour
resolve(freshData);
}
});
});
}
// Usage:
// getCachedData('user:123', () => fetchUserFromDB(123))
This approach reduces the load on the database and speeds up the application's response.