DEV Community

Cover image for Introduction to Redis
Divyanshu Tomar
Divyanshu Tomar

Posted on

Introduction to Redis

For a high traffic web service, it becomes a necessity for it to leverage some kind of caching mechanism. Caching is a way of storing computed data in memory so that future requests can be fulfilled right away. It also helps in avoiding any round trips to the data layer and computations on the application side if implemented with the right strategy. Redis and Memcached are two most popular memory-based stores available. In this post, we will explore some key concepts of Redis and go through some basic commands. Besides caching, Redis can be also used for other applications where there is a need for fast and frequent access to data.

Redis

redis logo

Redis is an in-memory data structure store supporting many data types like strings, hashes, sets, sorted sets, etc. Essentially, it is a key-value store.

Every type of value in Redis is stored against a key that is binary safe and it can be anything from an empty string to long hash string. Every application should follow a predetermined schema for naming Redis keys to avoid any naming conflicts.

Setting up Redis

Like every database, Redis contains a server for storing data in memory and clients which will execute commands against a server.
For setting up the server on your local machine, I will recommend using Docker as it is easy to get started. If you have Docker daemon running on your machine, run the following command:

docker run --rm -it --name local-redis -p 6379:6379 redis
Enter fullscreen mode Exit fullscreen mode

This will run a Docker container with name local-redis on your localhost with port 6379. It uses the official Redis docker image to run the container.

For the client, we can use the redis-cli for executing commands from a console on the Redis server. Open a new tab, and execute the following command to start a redis-cli session connected to local docker Redis server instance:

docker run -it --link local-redis:redis --rm redis redis-cli -h redis -p 6379
Enter fullscreen mode Exit fullscreen mode

Now we can start executing some basic Redis commands.

Commands

  • Setting a value:

    Syntax: SET <key> <value>
    Example: SET firstname Albert

  • Retrieve a value:

    Syntax: GET <key>
    Example: GET firstname

  • Check whether a key exists:

    Syntax: EXISTS <key>

  • Deleting a key:

    A key can be removed along with its associated memory using:
    DEL <key>
    This is a synchronous blocking operation.

    A better way to remove keys will be to unlink them whose associated memory can be collected by a garbage collector later on.
    UNLINK <key>

  • Setting a time to expire for key:

    EXPIRE <key> <seconds>
    PEXPIRE <key> <milliseconds>

  • Setting a key with check for existence and expiry in one go:

    Syntax: SET <key> <value> <EX seconds>|<PX milliseconds> NX|XX

    NX - set only when a key does not exist.
    XX - set only when key already exists.
    EX - sets expire time for the key in seconds.
    PX - sets expire time for the key in milliseconds.

    Example:

    SET firstname Albert EX 10 NX

    This will set the key firstname with string value "Albert" with an expiry time of 10 seconds only if the key does not exist.

  • Increment or Decrement an integer value:

    Redis provides a convenient way to increment or decrement integer values that may be used as counters.

    Syntax:
    INCR <key>
    DECR <key>
    INCRBY <key> <increment value>
    DECRBY <key> <decrement value>

    Example:
    SET counter 4
    INCRBY counter 6

    counter key will hold the value 4 initially, and after the second command, it will get incremented to 10.

All the above mentioned commands just deal with storing and manipulating of string or integer values. There are other data structure values such as hashes, sets, bit arrays, etc. that can be used to solve complex problems.

Real World Example

In a real-world application, you can use various programming language specific redis clients available for interacting with your Redis server from the application code.

We will be writing a simple Node based application that exposes an endpoint for getting user info against an userid. A JSON file will act as our datastore to keep things as simple as possible.

  • First, initialise a NPM repository by running npm init and install express and redis as dependencies.
  • Now, make a redis helper file that forms an instance of the redis client connected to our Redis server. We are also writing some cache helper methods here for our route handlers.

    redis cache helper file

  • In main app file, write a route handler that accepts an userid against which the user info is to be retrieved. Next, form a unique redis key using the userid. This key will always be the same for every request for a given userid. Check for existence of this key in the Redis cache, and return the response if found.

    main file index.js

  • Else, we will query the data from our data source and set the response data to Redis cache before sending it back as a response.

To have a look at the full code and tinker around with it, you can clone the following repository:

GitHub logo divyanshutomar / hello-redis

Express application that uses Redis for caching data

Hello Redis Example

An express application that demonstrates how redis can be utilized for caching data so that recurrent requests can be fulfilled right away.

Requirements

  • Node >= 8.x
  • Redis

Setup and Running

  • Clone this repo.
  • Install all the node dependencies using npm install.
  • Make sure you have local redis server instance running on localhost:6379. If not, you can easily start one by running the following command if you have docker daemon running on your machine.
docker run --rm -it --name local-redis -p 6379:6379 redis
  • Start the node service by running node index.js.



Congratulations! You have now learned the basics of Redis. If you'd like to take a deep dive, please have a look at the official redis docs.

Thank you for following along and I hope this post would have been useful for you.
Do follow me on Twitter to receive updates on such topics.

Top comments (6)

Collapse
 
leejinseok profile image
dooly

Thanks you article! What font do you used in source code?

Collapse
 
phathoang21 profile image
PhatHoang21

I also like the comment font, could you share with me the name of font?

Collapse
 
nikla profile image
Nikla

It looks to me like Operator Mono.
typography.com/blog/introducing-op...

Collapse
 
twof profile image
Alex Reilly

Wonderful summary! Are you planning on going over some other uses like Redis for websocket pubsub?

Collapse
 
divyanshutomar profile image
Divyanshu Tomar

Thanks Alex 😀. Well, I do have something like that in mind. I guess some use cases like leaderboard, applications using pubsub, etc. that gradually builds up from here.

Collapse
 
jcarlosr profile image
Juan Ramos

Sounds great! I hope we can see your next article soon.