Redis For Beginners
Published: 2024-06-10 18:14:05

## **Basic Overview 📖**

- **Why Redis is needed ??**

**Ans:** In contemporary application development, Redis plays a critical role by serving as a highly efficient in-memory data store. Its primary function is to cache computed data, which significantly reduces server load caused by excessive database queries. This caching mechanism ensures that frequently accessed data can be retrieved quickly, thus minimizing response times.

By integrating Redis, applications achieve two key optimizations:

**Reduced Query Load:** Redis stores frequently requested data in memory, alleviating the need for repeated queries to the primary database. This not only reduces the workload on the database server but also enhances overall system performance by avoiding bottlenecks associated with frequent data retrieval operations.

**Enhanced Response Time:** When data is cached in Redis, it can be returned to the user almost instantaneously. This rapid data access is crucial for applications requiring real-time responses, thereby improving user experience and making the application more responsive and efficient.

- **Define Redis:** Redis is an open source in-memory data store that can be used as a database, cache, or message broker. It's often used for caching web pages and reducing the load on servers.Redis run on the port number **6379**

- Redis have various data-types to store the data. It includes String,Set,List,Hash,etc

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

## **Redis Architecture: ⚙️**

![architecture](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ii7lvovy1v7meqm8qujh.png)

- **Cache Lookup:** Upon receiving a request, the system first checks Redis to see if the requested data is already cached. If the data is found (cache hit), it is immediately returned to the client, ensuring a fast response.

- **Cache Miss Handling:** If the data is not found in Redis (cache miss), the system then queries the persistent database to retrieve the necessary data. This ensures that the data retrieval process continues, albeit at a slightly slower pace compared to a cache hit.

- **Cache Priming:** Once the data is fetched from the persistent database, it is not only returned to the client but also stored in Redis. This step, known as priming the cache, ensures that subsequent requests for the same data can be served quickly from the cache, improving overall system performance.

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

## **Installation ⚒️**

- Firstly we create the redis container in Docker. For that you must have installed the Docker Desktop. You may visit my blog inorder to know how to install the Docker: [Click here](https://dev.to/jemmyasjd/setting-up-the-multi-container-application-with-docker-5gdj) 

- Open the Docker Desktop and open the command line and paste the following command. 

`docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:latest`

- As soon as you run the command you will find the container named "redis stack" running in the docker desktop. 


![container](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lcq02qh6a0cq0hla189a.png)

- Open the chrome and write **localhost:8001**, if you get following output then your redis installation is successfull: 


![redis stack](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kkmhnchwqi7kba8zd9b4.png)

- Now write the following command to get into the container shell : 

`docker exec -it redis-stack bash` and write `redis-cli --version` to get the redis version : 


![cli](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pve5rpilphutrbzh4s3y.png)

- Write the `redis-cli` command to get into the redis server


![cli enter](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w7shtputth4salm1jpe7.png)

- Now you are ready to write the redis command and execute. 

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

## **Setting up in VS Code in order to code along**

- Create a folder in vs code and do `npm install` in terminal. You have to install ioredis package to use it with nodejs. Run the following command to do it : 
`npm i ioredis`

- Make a file name client.js and write the code shown below: [code](https://github.com/jemmyasjd/redis/)

![client](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qtl2uzi3lhdst8osner8.png)

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

## **Commands for Strings:**

-> **set key value :** For eg. set name redis : To set the data

-> **get key:** for eg. get name => "redis" : To get the data


![set get](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kz4m1rmk35jh1aut7qab.png)



-> **set key value nx :** Here nx is a special command that will cached the data only if not already cached before.

-> **mget key1 key2 key3 :** To simultaneously get more than 1 cached data

-> **mset key1 "value1" key2 "value2":** To set multiple cached data simultaneously

![mset mget](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dhvp0xvm4w21qmqgr5kf.png)


-> **incr key :** to increment the value by 1

-> **incrby key n :** to increment value by n

![incr](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a9fjblk39kv5ijcetw67.png)

-> **expire key nsec :** will delete the key value after n sec

- Implementing string data type in nodejs: [code](https://github.com/jemmyasjd/redis/)

![example string](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nsufnbq808q05c13v9dm.png)

- Additional Commands : 

-> SETRANGE key offset value
-> GETRANGE key start end
-> SUBSTR key start end

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

## **Commands for List:**

-> **lpush key value:** push the element into the list from left side

-> **rpush key value:** push element into the list from right side

-> **lrange key start stop:** return the element in range 

-> **llen key value:** return the length of the list 


![push len](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ybz7vvcamuktqapsj111.png)

-> **lpop key value:** removes and return the head of the list


![lpop](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u6oq9yg7l9i80b8ubu2p.png)

-> **del key:** to delete the list

![del](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6cz8nvalxe2yw5kl3fwu.png)

- Similar like it there is other command to do operation from right side such as rpush, rpop, etc. 

- Additional Commands : 

-> LMOVE source destination <LEFT | RIGHT> <LEFT | RIGHT> : atomically moves elements from one list to another.
-> LRANGE key start stop :  extracts a range of elements from a list.
-> LTRIM key start stop : reduces a list to the specified range of elements.

- Implementing list data type in nodejs: [code](https://github.com/jemmyasjd/redis/)


![list node](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m7u9b9s701a3bc9reyln.png)

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

## **Commands for Set:**

-> **sadd key value:** to add value to the set

->**srem key value:** to remove from the set

-> **sismember key value:** to check that value present in set or not

-> **sinter key1 key2:** to get the common element between two set

-> **smembers key:** to get the all element in set

![set](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0q2xkm3a5eejuaoh3shz.png)

![get mem](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jixvquxtvswpyzc7g0vu.png)

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

## **Commands for Hash:**


-> **hset key field value field value:** to add the data to the hash set

-> **hget key field :** to get the value of particular field

->**hget all key:** to get all the value of key 

-> **hmget key field1 field2:** : to get the value of multiple field of key 

-> **hincrby key value n** : to increment field value by n 

- Implementing hash data type in nodejs: [code](https://github.com/jemmyasjd/redis/)


![hash node](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bdwbzjtrlhs5ym6se9y1.png)

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

## **Commands for Sorted Set:**

->**zadd key n value**: sort with according to the lowest value of n

-> **zrange key start stop:** to get all the value 

-> **zrevrange key start stop:** to get all the value in reverse order

-> **zrank key value:** to get the rank of the given value

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

## **Practical Example of Fetching todo list:**

### [**Code**](https://github.com/jemmyasjd/redis/) : 


![code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eqmoqhus0xr7b6gg9zhl.png)



- Before implementing Redis : 

![Before](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vkj80cqu4529wzz033cf.png)

- After implementinf Redis: 


![After](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xml1md9ibuu2quj4p24q.png)


- Thus we can see that after implementing redis the time taken to fetch the todos is very less compare to the previous one. This is because the data is already cached and get it directly from there.

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

## **Conclusion**

### Conclusion

In this blog, we delved into the essential role of Redis in modern application development. By serving as a high-performance in-memory data store, Redis significantly reduces server load and enhances response times through effective caching mechanisms. We explored Redis's architecture, which efficiently handles cache lookups, cache misses, and cache priming to ensure swift data retrieval and improved system performance. Furthermore, we provided detailed installation steps, essential commands for various Redis data types, and practical examples to illustrate its implementation in Node.js. The practical comparison demonstrated how integrating Redis dramatically reduces data fetching times, highlighting its value in optimizing application performance and user experience. For those interested in hands-on implementation, the provided GitHub repository offers a comprehensive guide to getting started with Redis.