Getting Started With Redis With Some Basic Commands

Redis is an open-source, in-memory data structure store that is widely used for caching, session management, real-time analytics, and more. It provides a rich set of commands that enable developers to manipulate data efficiently. In this blog post, we will explore the top few most used Redis commands and demonstrate how to use them in Node.js.
Prerequisites:
Before diving into the Redis commands, make sure you have Redis installed and running on your machine. Additionally, ensure that you have Node.js and npm (Node Package Manager) installed. We are using nodejs-redis library to communicate with Redis.
npm install redis
Create Redis Client
Lets first create Redis client using below code. This will connect to localhost
on port 6379
.
const redis = require('redis');
const client = redis.createClient();
Below code helps to connect to different host and port.
const redis = require('redis');
const client = redis.createClient({
url: 'redis://username:password@host:port'
});
SET:
The SET command is used to store a key-value pair in Redis. It allows you to set a value for a given key, overwriting any existing value if present.
async function setValue(key, value) {
try {
await client.set(key, value);
console.log('Value set successfully!');
}
catch (err) {
console.error(err);
}
}
await setValue('key', 'value');
GET:
The GET command retrieves the value associated with a specific key. In Node.js, you can use the get method of the Redis client to fetch the value.
async function getValue(key) {
try {
const value = await client.get(key);
console.log('Value:', value);
} catch (err) {
console.error(err);
}
}
await getValue('key');
MULTI/EXEC:
The MULTI/EXEC commands allow you to execute a group of Redis commands atomically. This ensures that all commands in the transaction are executed or none at all.
async function executeMulti() {
try {
await client.multi()
.set('key1', 'value1')
.set('key2', 'value2')
.exec();
console.log('Multi replies:', replies);
} catch (err) {
console.error(err);
}
}
await executeMulti();
INCR/DECR:
The INCR and DECR commands increment and decrement a numeric value associated with a key, respectively. These commands are handy for maintaining counters or tracking numerical values.
async function incrementCounter(key) {
try {
const newValue = await client.incr(key);
console.log('New value:', newValue);
} catch (err) {
console.error(err);
}
}
await incrementCounter('counter');
EXPIRE:
The EXPIRE command sets a time-to-live (TTL) for a key, after which it automatically expires. This is useful for implementing cache expirations.
async function setKeyWithExpiration(key, value, seconds) {
try {
await client.set(key, value, 'EX', seconds);
console.log('Key with expiration set successfully!');
} catch (err) {
console.error(err);
}
}
await setKeyWithExpiration('key', 'value', 60);
KEYS:
The KEYS command returns all keys matching a specified pattern. This can be helpful for retrieving keys with a specific naming convention. However, note that it can be an expensive operation on large Redis datasets.
async function getKeysByPattern(pattern) {
try {
const keys = await client.keys(pattern);
console.log('Keys:', keys);
} catch (err) {
console.error(err);
}
}
await getKeysByPattern('user:*');
DEL:
The DEL command deletes a key and its associated value from Redis.
async function deleteKey(key) {
try {
const reply = await client.del(key);
console.log('Key deleted:', reply);
} catch (err) {
console.error(err);
}
}
await deleteKey('key');
EXISTS:
The EXISTS command checks if a key exists in Redis. It returns 1
if the key exists, or 0
otherwise.
async function keyExists(key) {
try {
const exists = await client.exists(key);
console.log('Exists:', exists);
} catch (err) {
console.error(err);
}
}
await keyExists('key');
PUB/SUB:
Redis also supports a Pub/Sub (Publish/Subscribe) messaging pattern, which allows for real-time communication between different parts of an application. Here are the basic Pub/Sub commands:
PUBLISH:
The PUBLISH command publishes a message to a specific channel. All clients subscribed to that channel will receive the message.
function publishMessage(channel, message) {
client.publish(channel, message);
}
publishMessage('channel1', 'Hello, subscribers!');
publishMessage('channel2', 'Test');
SUBSCRIBE:
The SUBSCRIBE command subscribes the client to one or more channels. The client will receive messages published to these channels.
async function subscribeToChannels(...channels) {
try {
await client.subscribe(...channels);
console.log(`Subscribed to ${channels.length} channels`);
} catch (err) {
console.error(err);
}
}
await subscribeToChannels('channel1', 'channel2');
In addition to the previously mentioned commands, Redis is commonly used for caching purposes. Here are a few additional commands specifically useful for caching:
SETEX:
The SETEX command sets a key-value pair with an expiration time (in seconds). This is a convenient way to set a value in Redis and automatically have it expire after a certain duration.
async function setValueWithExpiration(key, value, seconds) {
try {
await client.set(key, value, 'EX', seconds);
console.log('Value set with expiration successfully!');
} catch (err) {
console.error(err);
}
}
await setValueWithExpiration('key', 'value', 60);
GETSET:
The GETSET command sets a new value for a key and returns the old value. This is often used in caching scenarios when you need to update a value and retrieve the previous value in an atomic operation.
async function updateAndGetOldValue(key, newValue) {
try {
const oldValue = await client.getset(key, newValue);
console.log(`Old value: ${oldValue}`);
} catch (err) {
console.error(err);
}
}
await updateAndGetOldValue('key', 'new value');
FLUSHALL:
The FLUSHALL command removes all keys from Redis, effectively clearing the cache. Be cautious when using this command as it removes all data.
async function clearCache() {
try {
await client.flushall();
console.log('Cache cleared successfully!');
} catch (err) {
console.error(err);
}
}
await clearCache();
Conclusion:
Redis provides a powerful set of commands that can significantly enhance your Node.js applications. In this blog post, we covered essential Redis commands, including SET, GET, MULTI/EXEC, INCR/DECR, EXPIRE, KEYS, DEL, EXISTS, PUB/SUB, and additional commands useful for caching. By leveraging these commands, we can efficiently manage our data in Redis, improving the performance and scalability of our applications.
This article is also enough for you to get started to learn about caching as we provided you the basic commands required.
Source code available in Github.