Junior — Middle
Použili ste Redis na účely cacheovania dát?
sobes.tech AI
Odpoveď od AI
Áno, Redis sa často používa na cacheovanie dát vďaka svojej vysokej rýchlosti práce s dátami v pamäti. V Node.js môžete použiť balík redis na komunikáciu so serverom Redis.
Príklad cacheovania výsledku dotazu:
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 na 1 hodinu
resolve(freshData);
}
});
});
}
// Použitie:
// getCachedData('user:123', () => fetchUserFromDB(123))
Tento prístup znižuje záťaž na databázu a zrýchľuje odozvu aplikácie.