What is redis?
The npm package 'redis' is a Node.js client for Redis, a fast, open-source, in-memory key-value data store for use as a database, cache, message broker, and queue. The package allows Node.js applications to interact with Redis servers using an asynchronous, event-driven model.
What are redis's main functionalities?
Connecting to Redis
This code sample demonstrates how to connect to a Redis server using the redis npm package. It requires the package, creates a client, and listens for the 'connect' event to confirm the connection.
const redis = require('redis');
const client = redis.createClient();
client.on('connect', function() {
console.log('Connected to Redis');
});
Setting and Getting Data
This code sample shows how to set a key-value pair in Redis and then retrieve the value associated with a key. The 'redis.print' callback is used to output the result of the 'set' operation.
client.set('key', 'value', redis.print);
client.get('key', function(err, reply) {
console.log(reply); // prints 'value'
});
Working with Lists
This code sample illustrates how to work with Redis lists by pushing values to the end of a list and then retrieving the entire list.
client.rpush(['list', 'value1', 'value2'], redis.print);
client.lrange('list', 0, -1, function(err, reply) {
console.log(reply); // prints ['value1', 'value2']
});
Publish/Subscribe
This code sample demonstrates the publish/subscribe capabilities of Redis. It creates a subscriber client that listens for messages on a channel and a publisher client that publishes a message to that channel.
const subscriber = redis.createClient();
const publisher = redis.createClient();
subscriber.on('message', function(channel, message) {
console.log('Message: ' + message + ' on channel: ' + channel);
});
subscriber.subscribe('notification');
publisher.publish('notification', 'Hello, World!');
Transactions
This code sample shows how to use Redis transactions to execute multiple commands atomically using the 'multi' and 'exec' methods.
client.multi()
.set('key', 'value')
.incr('counter')
.exec(function(err, replies) {
console.log(replies); // prints results of all commands
});
Other packages similar to redis
ioredis
ioredis is a robust, performance-focused, and full-featured Redis client for Node.js. It supports Redis Cluster, Sentinel, pipelining, Lua scripting, and more. Compared to the 'redis' package, ioredis offers a more modern interface with Promises support and better performance for certain operations.
node-redis
node-redis is another Redis client for Node.js that is designed to be easy to use. It may not have as many features as 'redis' or 'ioredis', but it provides a straightforward way to interact with Redis servers for simple use cases.
redis-mock
redis-mock is a library that simulates a Redis server for testing purposes. It implements most of the Redis commands and can be used as a drop-in replacement for the 'redis' package during testing, without the need for an actual Redis server.
:warning: Version 4 is still under development and isn't ready for production use. Use at your own risk.
Node Redis
A high performance Node.js Redis client.
Installation
npm install redis@next
Usage
Basic Example
import { createClient } from 'redis';
(async () => {
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');
})();
The new interface is clean and cool, but if you have an existing code base, you might want to enable legacy mode.
Redis Commands
There is built-in support for all of the out-of-the-box Redis commands. They are exposed using the raw Redis command names (HGET
, HSET
, etc.) and a friendlier camel-cased version (hGet
, hSet
, etc.).
await client.SET('key', 'value');
await client.GET('key');
await client.hSet('key', 'field', 'value');
await client.hGetAll('key');
Modifiers to commands are specified using a JavaScript object:
await client.set('key', 'value', {
EX: 10,
NX: true
});
Replies will be transformed to useful data structures:
await client.hGetAll('key');
await client.hKeys('key');
Unsupported Redis Commands
If you want to run commands and arguments that Node Redis doesn't know about (yet!) you can use .sendCommand
:
await client.sendCommand(['SET', 'key', 'value', 'NX']);
await client.sendCommand(['HGETALL', 'key']);
Blocking Commands
Any command can be run on a new connection by specifying the duplicateConnection
option. The newly created connection is closed when the command's Promise
is fulfilled.
This pattern works especially well for blocking commands—such as BLPOP
and BRPOPLPUSH
:
const blPopPromise = client.blPop(
client.commandOptions({ duplicateConnection: true }),
'key'
);
await client.lPush('key', ['1', '2']);
await blPopPromise;
Pub/Sub
Subscribing to a channel requires a dedicated Redis connection and is easily handled using events.
await subscriber.subscribe('channel', message => {
console.log(message);
});
await subscriber.pSubscribe('channe*', (message, channel) => {
console.log(message, channel);
});
await publisher.publish('channel', 'message');
Lua Scripts
You can define Lua scripts to create efficient custom commands:
import { createClient } from 'redis';
import { defineScript } from 'redis/dist/lib/lua-script';
(async () => {
const client = createClient({
scripts: {
add: defineScript({
NUMBER_OF_KEYS: 1,
SCRIPT:
'local val = redis.pcall("GET", KEYS[1]);' +
'return val + ARGV[1];',
transformArguments(key: string, toAdd: number): Array<string> {
return [key, number.toString()];
},
transformReply(reply: number): number {
return reply;
}
})
}
});
await client.connect();
await client.set('key', '1');
await client.add('key', 2);
})();
Legacy Mode
Need to use the new client in an existing codebase? You can use legacy mode to preserve backwards compatibility while still getting access to the updated experience:
const client = createClient({
legacyMode: true
});
client.set('key', 'value', 'NX', (err, reply) => {
});
await client.v4.set('key', 'value', {
NX: true
});
Cluster
Connecting to a cluster is a bit different. Create the client by specifying the root nodes in your cluster and then use it like a non-clustered client.
import { createCluster } from 'redis';
(async () => {
const cluster = createCluster({
rootNodes: [{
host: '192.168.1.1',
port: 30001
}, {
host: '192.168.1.2',
port: 30002
}]
});
cluster.on('error', (err) => console.log('Redis Cluster Error', err));
await cluster.connect();
await cluster.set('key', 'value');
const value = await cluster.get('key');
})();
Contributing
If you'd like to contribute, check out the contributing guide.
License
This repository is licensed under the "MIT" license. See LICENSE.