Redis is one of most known and used NoSQL databases among developers. Being open sourced it is equipped with over 20000 stars in GitHub and it’s found here. Redis is written in C and is mainly supported for Linux and related operating systems, but there are few ways to run Redis on Windows.

Let’s look at what Redis is used for and why Redis is different from other NoSQL databases.

NoSQL Databases and Redis

Redis is key-value database

Well contrary to popular belief, NoSQL actually mean ‘Not only SQL’.

Most of these databases doesn’t exactly define database structure like tables nor support queries such as SQL SELECT. NoSQL allows less restrictions on schema as data is mostly stored in JSON objects.

As shown in above table we can see that NoSQL databases can also be classified too. Each of these categories are for different use cases.

Key-Value database: Wikipedia

Here Redis is key-value database as shown. Each value in the store is mapped by a key. These values can vary from each other and doesn’t follow any particular structure. However no value can be retrieved unless key is known.

From Redis creators…

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with radius queries. Redis has built-in replication, Lua scripting, LRU eviction, transactions and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.

As mentioned Redis is in-memory store where the data is isn’t written to disk but kept in volatile RAM. This in-memory feature makes extremely fast access to data and therefore Redis is frequently used as cache and as secondary database to support primary database. However some persistence measures can be taken to deal with server failures, primarily by writing to disk at regular interval. Some other use cases include real time applications as well as MessageQueue applications.

Redis stores data using data structures and primary supports strings, hashes, lists, sets and sorted sets. Few more data structures are supported and may change with future versions.

Installing on Windows

As mentioned previously Redis is only supported to Linux by the creators. However installing on Windows is made feasible by 3rd parties and it’s even mentioned in Redis website.

In the GitHub page navigate to releases tab and find suitable version. Here choose from either .msior .zip installation files, where .zip file can be just expanded to use.

Just run redis-server.exe and the server will be exposed on 127.0.0.1 port 6379 by default.

The server should be kept running for the Redis database to be exposed.

In the same directory there is redis-cli.exe which is the client program to connect to Redis server. You could simply check whether that Redis server working properly by running ping command. Redis server would reply with PONG to ensure that it’s working perfectly.

Few more simple commands can be shown tried using Redis client.

set name "John" will insert record into Redis by ‘name’ key & ‘John’ as value.

By get name we will be able to get value of ‘name’ key.

incr & incrby operated on key ‘count’ without explicitly declaring as integer.

These Redis commands can also be tested inside the browser from this website. It’s easier to learn and play with Redis commands without any hassle.

GUI client tool for Redis

Even though Redis provides great CLI tool to work with Redis, we prefer GUI application for the ease of use. One such GUI client tool for Windows is Redis Desktop Manager.

We will be able to connect to running Redis server as a client and view what’s inside Redis database.

Redis Desktop Manager

Here we can see currently available keys and their values in the Redis database. Furthermore you will be able to add new keys or filter keys as you would using Redis client.

Redis Commands

All of Redis commands can be find here in their documentation. However for the ease of use, you could just filter out by data structure like strings, lists.

We will be going through some basic commands so we get an understanding of different types of data structures supported by Redis.

Strings

SET name "John"                         
GET name
EXISTS name // Check existence of key
DEL name // Delete key
EXPIRE name 5 // Delete key when expired
SET counter 100
INCRBY counter 25 // Increments by 25
DECR counter // Decrements by 1
MSET a 10 b 20 // Multiple SET
MGET a b // Multiple GET

Lists

Redis lists are implemented using linked-lists rather than arrays. Therefore insertion happens in constant time while searching for key may take more time. Linked-lists implementation is used by Redis it allows to add elements quickly even to long list. However sorted-lists in Redis is recommended if you application would consistently search for elements.

LPUSH myList 10                        // Add from left to head
RPUSH myList "str" // Add from right to tail
LRANGE myList 0 -1 // Range from 0 to -1
LTRIM myList 0 1 // To keep latest elements
RPOP myList // Pop last element

Hashes

Hash map consists of field-value pairs

HMSET user id 100 name "Smith"        // Setup hash with key "user"
HGET user id // Only 'id' field returned
HGETALL user

Sets

Sets are simply unordered collections of strings.

SADD mySet 10 45 12                  // Add elements to set
SMEMBERS mySet // Get all members of the set
SISMEMBER mySet 10 // Returns whether value exists

Sorted sets

Sorted sets are kind of in-between set and hash data structures, where each element consists of floating point value called ‘score’. This is ordered in term of this score value.

ZADD children 1992 "Sam"             // Birth-year acts as score
ZADD children 1997 "Tom"
ZRANGE children 0 -1 // Returns all in order
ZREVRANGE children 0 -1 withScores // Reverse order of ZRANGE
ZRANGEBYSCORE children -inf 1995 // Scores until 1993
ZREMRANGEBYSCORE children 1990 1995 // Remove from sorted set
ZRANK children "Tom" // Score rank of 'Tom'

Furthermore apart from these basic data structures, there are some more features such as Bitmaps, HyperLogLogs, Pub/Sub (Message service), Scripting (Lua)

Redis Client Libraries

Many client libraries can be found for different types of languages in this Redis page. However make sure to use recommended solution to prevent from any complications.

For .NET one of the recommended client is ServiceStack.Redis. Let’s test it using .NET Core console application. (Get started with .NET Core here…)

dotnet new console
dotnet add package ServiceStack.Redis.Core
dotnet restore
dotnet run
.NET with Redis

For NodeJS it is recommended to use package node_redis. Install package by npm install redis and use following server code.

NodeJS with Redis

With above simple code one could create Hash table named as HashValues and relevant keys are inserted to this table.

Redis as cache

As mentioned Redis is known to be used as cache for primary database. Here Redis is inbuilt supported to as Least Recently Used (LRU) cache or as Least Frequently Used (LFU) cache from Redis 4.0

Configuration such as maxmemory could be specified in redis.config or at run-time using redis-server --maxmemory 100mb. Further configuration include eviction policy by --maxmemory-policy allkeys-lru and likewise.

As an example Redis acts between NodeJS server application and MongoDB primary database, where Redis keeps track of recently accessed data. However cache data is preserved for quick access by restricting size of Redis database or validity of data. This caching mechanism is done by Redis as required.

NodeJS code with Redis cache and MongoDB database

In above NodeJS code in the method findBookByTitle method we will be searching whether the item is present at Redis cache. If not found we proceed to MongoDB database, and when it is found in the database it is saved into cache for future use.

It should be important to keep in mind to what’s in Redis if the same item is updated in MongoDB primary database. Else we would be retrieving old copy from Redis cache rather than modified value in database.

That’s introductory exposure to Redis, a NoSQL database used as cache. Hope you were able to understand basics of how to get started with Redis and feel free to leave comments below. Cheers!!!

Full Stack Developer | BiBi

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store