Hi I’m Shendi
Nodejs column
Nodejs operation cache database-Redis
In server-side development, cache database is also indispensable, which can improve program concurrency and facilitate subsequent expansion. Currently, the most commonly used one is Redis.
Install dependencies
Like the previous mysql, the most commonly used dependency of redis is redis
npm install redis
Depend on the corresponding github address: https://github.com/redis/node-redis
This is the official NodeJS connection guide from Redis https://redis.io/docs/clients/nodejs/
For information on the installation and use of Redis, you can read this article: https://sdpro.top/blog/html/article/1023.html
Connection example
The following is the official sample code
import {<!-- --> createClient } from 'redis'; const client = createClient(); client.on('error', err => console.log('Redis Client Error', err)); await client.connect(); await client.set('key', 'value'); const value = await client.get('key'); await client.disconnect();
The above code connects to localhost:6379. To connect to other addresses, use the following format
redis[s]://[[username][:password]@][host][:port][/db-number]
For example
createClient({<!-- --> url: 'redis://alice:[email protected]:6380/0' });
Among them username account, password, host host address, port port, database subscript used by db-number, default 0
For more information refer to the documentation: client configuration guide
To check if the client is connected and ready to send commands, use client.isReady, which returns a boolean value. client.isOpen is also available. This function returns true when the client’s underlying socket is open, and false when it is not open (for example, when the client is still connected or reconnecting after a network error).
The operations of the library are basically asynchronous. If await is used above, then the current function needs to be set to async asynchronous, for example
async function test() {<!-- --> await client.connect(); }
Because it is asynchronous, we need to control the error handling ourselves.
Let me mention here, the asynchronous here is all the returned Promise, so you can use the Promise method
Rather than destructuring assignment, I prefer the following approach
var redis = require("redis"); const client = redis.createClient(); client.on('error', err => console.log('Redis Client Error', err)); await client.connect(); await client.set('key', 'value'); const value = await client.get('key'); await client.disconnect();
No need to worry about connections and connection pools
Node_redis manages connections automatically, so there is no need to wait for connections or callbacks. Since both Node.js and Redis are effectively single-threaded, there is no need to use multiple client instances or any pooling mechanism with few exceptions; the most common exceptions are if you use Pub/Sub subscriptions, or use streams or lists To block, you need to have a dedicated client to receive these long-running commands.
For example, if you connect to an incorrect Redis address, you will be reconnected all the time.
Use
The library provides built-in support for all Redis commands out of the box. These commands are exposed using the original Redis command names (HSET, HGETALL, etc.) and a more friendly camelCase version (hSet, hGetAll, etc.):
//Original redis command await client.HSET('key', 'field', 'value'); await client.HGETALL('key'); // Friendly js command await client.hSet('key', 'field', 'value'); await client.hGetAll('key');
To specify modifiers for a command, you can use a JavaScript object:
await client.set('key', 'value', {<!-- --> EX: 10, NX: true });
The above EX is the expiration time in seconds. When NX is true, it will be set when the key does not exist. For more parameters, please refer to https://sdpro.top/blog/html/article/1023 for more parameters. .html
The retrieved content will be converted into useful structures
await client.hGetAll('key'); // { field1: 'value1', field2: 'value2' } await client.hVals('key'); // ['value1', 'value2']
The library also supports Buffer
:
await client.hSet('key', 'field', Buffer.from('value')); // 'OK' await client.hGetAll( commandOptions({<!-- --> returnBuffers: true }), 'key' ); // { field: <Buffer 76 61 6c 75 65> }
If you want to run a command that Node Redis doesn’t support (yet!), use .sendCommand():
await client.sendCommand(['SET', 'key', 'value', 'NX']); // 'OK' await client.sendCommand(['HGETALL', 'key']); // ['key1', 'field1', 'key2', 'field2']
Transaction (Multi/Exec)
Start a transaction by calling .multi() and then chain your commands together. Once done, call .exec() and you will get an array containing your results:
await client.set('another-key', 'another-value'); const [setKeyReply, otherKeyValue] = await client .multi() .set('key', 'value') .get('another-key') .exec(); // ['OK', 'another-value']
You can also watch keys by calling .watch(). If any of the monitored keys change, the transaction will be aborted.
To learn more about transactions, check out the Isolated Execution Guide.
Event
The Node Redis client class is a Nodejs EventEmitter that emits an event every time the network status changes:
Name | When it happens | Listening parameters |
---|---|---|
connect |
Start connection with server | No arguments |
ready |
The client is ready to use | No arguments |
end |
The connection has been closed (via .quit() or .disconnect() ) td>
| No arguments |
error |
An error occurred – usually network Problems, such as “Socket closed unexpectedly” | (error: Error) |
reconnecting |
The client is trying to reconnect to the server | No arguments |
sharded-channel -moved |
See here | See here |
Supported versions
Version | Whether it is supported |
---|---|
7.0.z | |
6.2.z | |
6.0.z | |
5.0.z | |
< 5.0 | ? |
Node Redis should work with older versions of Redis, but it has not been fully tested and we cannot provide support.
The windows version of redis I use is currently 3.0.504
, and there are no problems for the time being.
Error resolution
Connection error ErrorReply: ERR wrong number of arguments for auth’ command
This error occurred by calling createClient({url: “”}), because redis did not set an account, only a password, and the url user password given above has it, so I searched for the default account of redis. to default
… but no account is set, the account number should be left blank
Link settings are solved as follows
redis://:password@localhost:6379
END