Redis Notes (Redis-CLI, Redis with NodeJS)

 

Redis (Remote Dictionary Server) is an open source NoSQL in-memory, key-value data store. All Redis data resides in ram memory, which enables low latency and high throughput data access. Unlike traditional databases, In-memory data stores don’t require a trip to disk, reducing engine latency to microseconds. 

Redis delivers sub-millisecond response times, enabling millions of requests per second for real-time applications in industries like gaming, ad-tech, financial services, healthcare, and IoT. 

Redis store data inside the volatile ram, it can be entirely ephemeral with no persistence at all. Our data is only available while the server is running, and if for some reason the server was terminated or rebooted our data is lost.

The Redis stores the data as key-value pairs. It is similar to a single JSON object. We create keys and store values associated with each key.

NOTE : The Redis is not official supported on Windows OS, but you can run redis on Windows using WSL2. In production you'll mostly run redis on Linux.

Once you're running Ubuntu on Windows (with WSL2), you can install Redis using the below commands.


// https://redis.io/docs/getting-started/installation/install-redis-on-windows/

sudo apt-add-repository ppa:redislabs/redis
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install redis

// start redis server
sudo service redis-server start



---------------------------------------------------------------------------------------------------------------


Connecting to Redis Server

There are many ways to connect to a Redis server, below are some of the ways to connect to one :

  • Redis-CLI - The default command-line tool for redis database.
  • RedisInsight - A GUI tool to manage the redis database.
NOTE : Some of the cloud providers that provide managed redis servers are RedisLabs, AWS Elasticache, Digital Ocean Redis etc

Connections in Production

In production environment,a client will be using an application written in any programming language like python,javascript etc. In such cases we wont be using the above mentioned tools,rather we'll use special modules which will simply take in the database info (user,password) and make a connection to  execute a given task.

Below we show how to connect to Redis Server using Python and Javascript :


// Connect and set a key inside a Redis server in Node.JS

const redis = require('redis');
const client = redis.createClient({
host: '<hostname>',
port: <port>,
password: '<password>'
});


client.set('foo', 'bar', (err, reply) => {
if (err) throw err;
console.log(reply);

client.get('foo', (err, reply) => {
if (err) throw err;
console.log(reply);
});
});



// Connect and set a key inside a Redis server in Python

import redis

client = redis.Redis(
host='hostname',
port=port,
password='password')


client.set('foo', 'bar')
value = r.get('foo')
print(value)


---------------------------------------------------------------------------------------------------------------


Redis-CLI commands

Below we'll see some common commands while using redis-cli tool.


1] Make a Connection

By default redis-cli connects to the server at the address 127.0.0.1 with port 6379. You can change this using several command line options. 


$ redis-cli -h <hostname> -p 6390 -a <password>

$ redis-cli -u redis://username:password@host:port


2] CRUD Commands

Below we se hwo to perform create,read,update and delete operations with redis key-store.


# SET <key> <value>
SET username "DeepeshDM"

# GET <key>
GET username

# Update an existing key
SET username "RohanSinghRS"

# DEL <key>
DEL username

# RENAME OLD_KEY_NAME NEW_KEY_NAME
RENAME username UserName

# Find keys that match a pattern
KEYS *tutorial*

# Get data type of value stored in key
TYPE <key>


3] Key Expiration

Normally Redis keys are created without an associated time to live. The key will simply live forever, unless it is removed by the user in an explicit way, for instance using the DEL command.

The EXPIRE command is used to set an expiration timer to a key. Technically it's not a timer, but a kill timestamp beyond which the key will always return null unless it's set again. Return 1 if timeout is set , and 0 if key does'nt exists.


# Expire KEY_NAME TIME_IN_SECONDS
SET username "DeepeshDM"
EXPIRE username 600

The TTL command can be used to learn how much time the key has to live. It returns the following values :

  • TTL will return -1 if the key exists but doesn't have an expiration
  • TTL will return -2 if the key doesn't exist
  • TTL will return time to live in seconds if the key exists and will expire

# Expire KEY_NAME TIME_IN_SECONDS
SET username "DeepeshDM"
EXPIRE username 600


# Get TTL of a key
TTL username // returns 600


---------------------------------------------------------------------------------------------------------------


Redis Data Types

Redis stores everything in string or in its string representation, even Integers are stored as strings. Below are some of the common data types in redis :

  • Strings
  • Lists
  • Sets
  • Sorted Sets
  • Hashes
  • Bitmaps
  • Geospatial Indexes

1] Strings

We can store strings and Integers in redis using GET and SET methods.


# Strings
SET username "tutorialspoint"
SET age 19
GET username
GET age


2] Lists

Redis Lists are simply lists of strings, sorted by insertion order. It is possible to add elements to a Redis List pushing new elements on the head (on the left) or on the tail (on the right) of the list.

  • RPUSH: This command adds a new element at the right of the list.

  • LPUSH: This command adds a new element at the left of the list.

  • RPOP: This command removes an element at the right, or tail of the list.

  • LPOP: This command removes an element at the left, or head of the list.

  • LINDEX: This command retrieves the item at the specified position in the list.

  • LRANGE: This command retrieves a subset of list elements based on the provided “start” and “stop” offsets.


# Left Push List
LPUSH <listname> element
LPUSH animals "Dogs"
LPUSH animals "Tiger"
LPUSH animals "Cats" # ["Cats","Tiger","Dogs"]
LPOP animals # ["Tiger","Dogs"]

# Right Push List
RPUSH <listname> element
RPUSH animals "Dogs"
RPUSH animals "Tiger"
RPUSH animals "Cats" # ["Dogs","Tiger","Cats"]
RPOP animals # ["Dogs","Tiger"]

LINDEX animals 1 # Dogs


3] SETS

Redis Sets are an unordered collection of strings. In Redis, you can add, remove etc members in O(1) time complexity. We use the below methods for sets in redis :

  • SADD: This command inserts one or more elements inside the set.

  • SMEMBERS: This command displays all values inside the set.

  • SREM: This command removes a specified element from the list.


# Create a Set
SADD friends "Rohan" "Kiran" "Amit"
SMEMBERS friends # "Rohan" "Kiran" "Amit"
SREM friends "Kiran"
SMEMBERS friends # "Rohan" "Amit"


4] Hashes

In Redis we can also have a key-value pair object associated with a key.


# Syntax
HSET <hash-name> <key> <value>

# Create a hash and set field
HSET person firstname "Deepesh"
HSET person lastname "Mhatre" age 19

# Get key values
HGET person firstname # Deepesh
HGETALL person
HKEYS person
# Delete specific field
HDEL person lastname


---------------------------------------------------------------------------------------------------------------


Redis NodeJS

Below we display some common operations to be performed on redis server hosted on RedisLabs cloud using NodeJs.


1] Connect to Redis-Server


// redisClient.JS

const redis = require('redis');

async function createRedisClient () {
   
  const client = redis.createClient({
    url: "redis://deepeshdm:8609156$@redis-cloud.redislabs.com:17017",
  });

  client.on('connect', () => console.log('Connected to REDIS!'));
  client.on('error', (err) => console.log('Error connecting to REDIS: ', err));

  await client.connect();

  return client;
}

module.exports = createRedisClient();


2] Read & Write Values

i] Strings

 
 
 const redisClient = require("./redisClient");

 // SET a value
 redisClient.then((client) => {
   client.set("Movie", "Doraemon").then(() => {
     console.log("Value Set !");
   });
 });


 // GET a value
 redisClient.then((client) => {

   console.time();
   client.get("Movie").then((output) => {
     console.log("Result : ", output);
   });
   console.timeEnd();
 });


ii] Hashes

 
const redisClient = require("./redisClient");

 // SET a value
 redisClient.then((client) => {

    const person = {
        firstName:"John",
        lastName:"Doe",
        age:50,
        skills : ["Programming","Reading","Biking"],
        eyeColor:"blue"};

   client.hSet("Person_Details",person).then(() => {
     console.log("Value Set !");
   });
 });


 // GET all values
 redisClient.then((client) => {

   console.time();
   client.hGetAll("Person_Details").then((output) => {
     console.log("Result : ", output);
   });
   console.timeEnd();
 });

 


---------------------------------------------------------------------------------------------------------------




Comments

Popular posts from this blog

React Js + React-Redux (part-2)

React Js + CSS Styling + React Router (part-1)

ViteJS (Module Bundlers, Build Tools)