Ili kushughulikia shughuli za data kutoka Redis, NodeJS unahitaji kutumia Redis maktaba kwa NodeJS kama vile redis
au ioredis
kisha kufanya shughuli za kimsingi kama vile kuongeza, kusasisha, kufuta na kuuliza data katika Redis. Chini ni mwongozo rahisi wa kufanya shughuli hizi:
Hatua ya 1: Sakinisha Redis maktaba
Kwanza, sasisha Redis maktaba kwa kutumia npm:
npm install redis
Hatua ya 2: Unganisha kwa Redis
nambari yako NodeJS, tengeneza muunganisho kwa Redis:
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);
});
Hatua ya 3: Ongeza, Sasisha, Futa na Data Data
Baada ya kusanidi unganisho, unaweza kufanya shughuli za data kama ifuatavyo:
Ongeza data :
// Store a value in Redis with the key 'name' and value 'John'
client.set('name', 'John',(err, reply) => {
if(err) {
console.error('Error:', err);
} else {
console.log('Stored:', reply);
}
});
Data ya hoja:
// Retrieve a value from Redis with the key 'name'
client.get('name',(err, reply) => {
if(err) {
console.error('Error:', err);
} else {
console.log('Retrieved:', reply);
}
});
Sasisha data :
// Update the value of the key 'name' to 'Alice'
client.set('name', 'Alice',(err, reply) => {
if(err) {
console.error('Error:', err);
} else {
console.log('Updated:', reply);
}
});
Futa data :
// Delete the data with the key 'name'
client.del('name',(err, reply) => {
if(err) {
console.error('Error:', err);
} else {
console.log('Deleted:', reply);
}
});
Kwa kutumia Redis maktaba katika NodeJS, unaweza kushughulikia kwa urahisi shughuli za data ndani Redis na kuchukua fursa ya uwezo wake wa kuhifadhi data kwa haraka na bora katika programu yako.