Home >Database >Redis >How to use Node.js and Redis to implement addition, deletion, modification and query operations

How to use Node.js and Redis to implement addition, deletion, modification and query operations

WBOY
WBOYforward
2023-05-30 19:37:471179browse

What is Node.js

Node.js is a JavaScript runtime environment built on the Chrome V8 JavaScript engine. It allows developers to easily build scalable web applications by running JavaScript code on the server side. HTTP module is one of the useful modules provided in Node.js that can be used to handle network communication between client and server.

What is Redis

Redis is a memory-based data storage system that can be used to quickly store and query a variety of data, including caches and message queues. Redis supports a variety of data types, such as strings, lists, sets, etc., and provides various APIs to allow developers to easily operate on data.

Implementing CRUD operations

For web applications, one of the most common operations is CRUD (CRUD).

First, we need to install the Redis client library. The redis module can be installed using the npm package manager:

npm install redis --save

Next, we need to use the redis.createClient function to create a Redis client instance, which will be used to communicate with the Redis server:

var redis = require('redis');
var client = redis.createClient();

Now, we can start to implement add, delete, modify and check operations.

Add data

Storing data to the Redis server is the first step to save data using Redis. Use the hset command to add data to Redis:

client.hset('user:1', 'name', 'John Doe', 'age', 30, redis.print);

This will add a hash named "user:1" which contains the keys "name" and "age" and set them to "John Doe" respectively ” and 30. The response returned by Redis can be printed using redis.print as the last parameter. If successful, it will output OK.

Update data

For update operations, we need to use the hset command. It will overwrite the existing field value:

client.hset('user:1', 'age', 31, redis.print);

This will update the key "age" of the hash named "user:1" with a value of 31.

Getting data

You can use the hgetall command to get all the fields in the hash:

client.hgetall('user:1', function (err, obj) {
  console.dir(obj);
});

This will output all the fields of the hash named "user:1" and its corresponding value.

Delete data

Finally, to delete the data in Redis, use the hdel command:

client.hdel('user:1', 'name', redis.print);

This will delete the data in the hash named "user:1" "name" field.

The above is the detailed content of How to use Node.js and Redis to implement addition, deletion, modification and query operations. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete