DEV Community

Ahmet Burhan Simsek
Ahmet Burhan Simsek

Posted on

Redis — The High-Performance In-Memory Data Store

Redis is a popular open-source in-memory data store that is widely used by developers to store and manipulate data in real-time. Redis is a flexible data store that can be used as a cache, message broker or database, among other things. Many developers favor Redis because of its speed, adaptability and scalability.

What is Redis?

Redis is an in-memory data store made specifically for real-time data storing and manipulation. Redis, which stands for Remote Dictionary Server, is a key-value store that enables the usage of keys and values to store and retrieve data. In contrast to conventional databases that keep data on disk, Redis is a NoSQL database. Redis, on the other hand, keeps data in memory, which speeds up access and manipulation.

How does Redis work ?

Redis is made to be quick and easy to use. It is constructed using an event-driven architecture that manages many client connections using a single thread. Redis stores information in key-value pairs, where the key represents the data’s actual value while the value is a special identifier for the data. Data structures supported by Redis include strings, hashes, lists, sets, and sorted sets.

Redis is an in-memory, server-based key-value data store that is intended to be quick and effective. Redis has a straightforward key-value model, where the key is a single identifier and the value can be any of a number of different types, including texts, lists, hashes, sets, or sorted sets.

When a client sends a request to Redis, the server — which may be running remotely or on the same machine as the client — processes the request. The Redis server keeps all of the data in memory, enabling quick access.

    +-----------+
    |  Clients  |
    +-----------+
         |          +------------+
         |          | Redis      |
         +--------->| Server     |
                    |            |
                    | Key-Value  |
                    | Store      |
                    +------------+
Enter fullscreen mode Exit fullscreen mode

The Redis server manages incoming client connections via a single-threaded event loop. A client connects to Redis and submits a request, which the Redis server parses and handles. The client is then sent a response by the Redis server.

It is incredibly quick because it stores data in an in-memory data structure. Redis uses a variety of methods to control memory usage and guarantee data durability, but since all data is kept in memory, this is the only option.

Redis implements the LRU (Least Recently Used) eviction approach to control memory use, which implies that when the memory limit is reached, Redis deletes the least recently used keys from memory. Redis can distribute data across other machines thanks to its capabilities for sharding.

Redis offers snapshotting and journaling as two types of persistence to guarantee data lifespan. Whereas journaling logs each write activity, snapshotting entails periodically writing the complete dataset to disk. Redis also offers replication and clustering to offer high availability and redundant data.

Benefits of using Redis

Using Redis has a number of advantages, such as:

1- High Performance: Redis is designed to be fast and efficient. It can handle millions of requests per second and can store and retrieve data in microseconds.

2- Scalability: Redis can scale horizontally by adding more nodes to a cluster, making it ideal for high-traffic applications.

3- Flexibility: Redis supports a wide range of data structures, making it versatile and flexible. It can be used as a cache, message broker, or database, among other things.

Using Redis in .NET Project with C

Using Redis in C# projects are very easy.

First you need to add NuGet package called “StackExchange.Redis” to your project. This package is high performance Redis client which incorporates both synchronous and asynchronous usage.

Here is the sample code with Redis usage in C#

// Connect to the Redis server
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379");

// Get a database instance
IDatabase db = redis.GetDatabase();

// Set a value
db.StringSet("mykey", "Hello Redis!");

// Get a value
string value = db.StringGet("mykey");

Console.WriteLine(value); // Outputs "Hello Redis!"

// Create a hash
HashEntry[] hashEntries = new HashEntry[] {
        new HashEntry("name", "John"),
        new HashEntry("age", 30)
    };
db.HashSet("myhash", hashEntries);

// Get a hash value
string name = db.HashGet("myhash", "name");
int age = (int)db.HashGet("myhash", "age");

Console.WriteLine($"{name} is {age} years old."); // Outputs "John is 30 years old."

// Create a list
db.ListRightPush("mylist", "item1");
db.ListRightPush("mylist", "item2");
db.ListRightPush("mylist", "item3");

// Get list values
string[] listValues = db.ListRange("mylist").ToStringArray();

foreach (string item in listValues)
{
    Console.WriteLine(item); // Outputs "item1", "item2", "item3"
}

// Remove all data
redis.GetServer("127.0.0.1", 6379).FlushDatabase();

// Disconnect from the Redis server
redis.Close();
Enter fullscreen mode Exit fullscreen mode

In this example, we first connect to the Redis server using the ConnectionMultiplexer class. We then get a database instance using the GetDatabase method, which allows us to interact with the Redis server.

Next, we set a value using the StringSet method and retrieve it using the StringGet method. We then create a hash using the HashSet method and retrieve its values using the HashGet method.

Finally, we create a list using the ListRightPush method and retrieve its values using the ListRange method. We also demonstrate how to remove all data from the Redis database using the FlushDatabase method and how to disconnect from the Redis server using the Close method.

The output of the program should be;

Hello Redis!
John is 30 years old.
item1
item2
item3
Enter fullscreen mode Exit fullscreen mode

Also we can see the keys and values we stored in Redis through redis-cli;

What is redis-cli?

redis-cli is a command-line interface (CLI) tool that allows you to interact with Redis, a popular in-memory key-value data store. With redis-cli, you can send commands to a Redis server and receive the responses directly in your terminal.

Using redis-cli, you can perform a wide range of operations on Redis data structures, including setting and retrieving keys, deleting keys, incrementing and decrementing values, and much more. redis-cli is a powerful tool for working with Redis data, and is widely used by developers and system administrators who work with Redis on a regular basis.

redis-cli comes installed with Redis by default, so if you have Redis installed on your system, you should be able to start using redis-cli right away. To launch redis-cli, simply open a terminal window and type redis-cli at the command prompt. Once you're connected to a Redis server, you can start sending commands and receiving responses.

Here are some common redis-cli commands that are good to know;
SET key value: Sets a key in Redis with a given value. For example:

SET name "John"
Enter fullscreen mode Exit fullscreen mode

GET key: Retrieves the value of a key in Redis. For example:

GET name
Enter fullscreen mode Exit fullscreen mode

DEL key: Deletes a key in Redis. For example:

DEL name
Enter fullscreen mode Exit fullscreen mode

KEYS pattern: Returns a list of keys that match the given pattern. For example:

KEYS *user*
Enter fullscreen mode Exit fullscreen mode

HSET key field value: Sets the value of a field in a Redis hash stored at the specified key. If the field does not exist, it is created. If the key does not exist, a new hash is created with the specified field and value. For example:

HSET user:id:1234 name "John Smith" age 30 email "john.smith@example.com"
Enter fullscreen mode Exit fullscreen mode

HGETALL key: Returns all fields and values of a hash stored at the specified key. For example:

HGETALL user:id:1234
Enter fullscreen mode Exit fullscreen mode

RPUSH key value [value …]: Appends one or more values to the end of a Redis list stored at the specified key. If the key does not exist, a new list is created with the specified values. For example:

RPUSH list 1 2 3 4 5
Enter fullscreen mode Exit fullscreen mode

LRANGE key start stop: Returns a range of elements from a list stored at the specified key. For example:

LRANGE list 0 2 //gets starting from 0th element to 2nd element

//1 2 3 will return from the list above
Enter fullscreen mode Exit fullscreen mode

FLUSHALL: Deletes all keys in Redis. Use with caution!

FLUSHALL
Enter fullscreen mode Exit fullscreen mode

How to install Redis in Windows?
Installing Redis on Windows devices is not that straightforward. Redis is not officially supported on Windows so you need to enable WSL2 (Windows Subsystem for Linux).

WSL2 lets you run Linux binaries natively on Windows. For this method to work, you’ll need to be running Windows 10 version 2004 and higher or Windows 11.

Step 1: Install Ubuntu with wsl command in Windows;

wsl --install -d Ubuntu
Enter fullscreen mode Exit fullscreen mode

Step 2: After Ubuntu installation completes, update Ubuntu and install Redis;

sudo apt-get update
sudo apt-get install redis
Enter fullscreen mode Exit fullscreen mode

*These commands in step 2 needs to be executed in Ubuntu terminal which will appear after step 1.

Step 3: Start redis-server in Ubuntu terminal;

sudo service redis-server start
Enter fullscreen mode Exit fullscreen mode

Step 4: Connect to Redis with redis-cli;

redis-cli
Enter fullscreen mode Exit fullscreen mode

If you complete all steps above successfuly, you can test redis-cli with ping command which will get result from Redis;

For further installation details, you can refer to official documentation or feel free to reach me out 😉

In conclusion, Redis is a powerful in-memory key-value data store that offers quick speed, excellent scalability, and a variety of features and data types. It is frequently used by programmers and system administrators to create quick, scalable, and dependable programs that can deal with massive amounts of data.

We’ve covered what Redis is, how it functions, and some of the main advantages of utilizing Redis in this article. Also, we have discussed some typical Redis commands, how to install Redis on Windows and how to use Redis in .NET with the C# language.

I hope this article was instructive and useful to you. There’s always more to learn about this powerful technology, whether you’re just getting started with Redis or an expert user. I appreciate you taking the time to read this post and I strongly recommend you to use **Redis **in all of your projects and apps needs it’s functionalities.

Please feel free to leave a comment below if you have any questions or suggestions. 🤗

Good luck and happy coding 😎

Top comments (0)