Amfani Redis azaman Cache a cikin NodeJS: Ƙarfafa Ayyuka

Amfani Redis azaman cache a ciki NodeJS hanya ce mai inganci don haɓaka aikin aikace-aikacen. Cache tsarin adana bayanai na wucin gadi ne wanda ke taimakawa rage lokacin da ake ɗauka don neman bayanai daga tushen asali(misali, bayanai) da haɓaka saurin amsa aikace-aikacen.

Anan ga matakan da za a yi amfani da su Redis azaman cache a cikin NodeJS aikace-aikacen:

Mataki 1: Shigar da Redis ɗakin karatu

Da farko, kuna buƙatar shigar da Redis ɗakin karatu don NodeJS amfani da npm:

npm install redis

 

Mataki 2: Ƙirƙiri haɗi zuwa Redis

n lambar ku NodeJS, ƙirƙirar haɗi don Redis amfani da ɗakin karatu da aka shigar:

const redis = require('redis');  
  
// Create a Redis connection  
const client = redis.createClient({  
  host: 'localhost', // Replace 'localhost' with the IP address of the Redis server if necessary  
  port: 6379, // Replace 6379 with the Redis port if necessary  
});  
  
// Listen for connection errors  
client.on('error',(err) => {  
  console.error('Error:', err);  
});  

 

Mataki 3: Yi amfani Redis azaman cache

Bayan saita haɗin, zaku iya amfani Redis da azaman cache don adanawa da dawo da bayanai.

Misali, don adana ƙima a cikin Redis, zaku iya amfani da set hanyar:

// Store a value in Redis for 10 seconds  
client.set('key', 'value', 'EX', 10,(err, reply) => {  
  if(err) {  
    console.error('Error:', err);  
  } else {  
    console.log('Stored:', reply);  
  }  
});  

Don dawo da ƙima daga Redis, zaku iya amfani da get hanyar:

// Retrieve a value from Redis  
client.get('key',(err, reply) => {  
  if(err) {  
    console.error('Error:', err);  
  } else {  
    console.log('Retrieved:', reply);  
  }  
});  

Yin amfani Redis da azaman cache yana taimakawa haɓaka aikin aikace NodeJS -aikacen ta hanyar rage lokacin neman bayanai daga tushen asali da ƙara saurin amsawa. Keɓance lokacin ajiya na wucin gadi na bayanai don dacewa da buƙatun aikace-aikacen don ingantaccen aiki.