Redis: Introduction

Neelesh Dwivedi
Webtips
Published in
3 min readJul 3, 2020
Introduction to Redis
Photo by Arnold Francisca on Unsplash

Redis is an in-memory data structure that is used for caching. In-memory means that the data is not persistent and it is lost once we switch off the machine. So it is advisable to only store values that do not need persistence. We are going to have a basic introduction to Redis in this article. We are not going to invest our time in discussing how to install Redis on your local system. For this, you can refer to this excellent article by the digital ocean.

Now after we have successfully set up Redis on our system, let’s talk about how Redis stores data.

Redis stores data in a key-value format.

Redis key-value pair

to set and get values from Redis we use the get and set functions provided to us by Redis client. Let us write some code for getting and setting values in and from Redis.

Setting and Getting values from Redis

Let us discuss what is happening in the code above.

We are requiring the Redis npm.

We are setting a variable redisUrl with the value of the Redis URI, which is “redis://127.0.0.1:6379” by default.

We are creating a Redis client by calling the createClient function of Redis and passing in the Redis URL as the argument.

We are then setting up a key-value pair inside the Redis server with the help of set function which requires two arguments: key and value

We are getting the value from a key inside of Redis by using the get function which requires two arguments: a key and a callback.

If we run the following code with node redisDemo.js, we are going to get the following output

there

which is the value stored inside the ‘hi’ key.

Creating hashes with Redis

Redis can not only store key-value pairs but can also store hashes. We need to use the hset and hget functions to save and retrieve values from Redis hashes.

Storing and retrieving data from Redis hashes

Let us write some code to showcase Redis hashes in action.

hashing in Redis

Here we are setting up value in a hash using hset function and getting value using hget function. Please note that we can only fetch the last value from the hash and can not fetch the sub hash.

There is one important catch with redis. It can only store strings and number values only. So if we want to store JSON objects or arrays we may need to first stringify them and the save in redis.

Conclusion

In this article, we were introduced to how we can set up Redis and use Redis for setting and getting values. We also learned how we can use Redis hashes to store nested values.

This will be it for today. If you liked the article please give a clap.

--

--

Neelesh Dwivedi
Webtips
Writer for

A burning sense of passion is the most potent fuel for your dreams.