Redis Hashes and RedisJSON for Caching Your Data

Comparing Techniques for Effective Redis Data Management

Sasha Marfut
Geek Culture

--

Photo by Joshua Sortino on Unsplash

In today’s article we will look at the most common way of storing data in the Redis cache, its drawbacks and ways to solve them.

One of the most common uses of the Redis instance is to cache data loaded from a database or other source.

public class Model
{
public int Id { get; set; }

public string Value { get; set; }
}

Suppose our application implements the Cache-Aside pattern. It loads the collection of Model objects from the database and writes it to the cache if it is empty.

In what format can the application save this collection to Redis cache? The easiest and most commonly used way to do this is to serialize the entire collection into a JSON string (other formats are also possible like Protobuf, BSON, Avro) and save it as follows:

var redis = ConnectionMultiplexer.Connect(
new ConfigurationOptions
{
EndPoints = { "localhost:6379" },
});

IDatabase db = redis.GetDatabase();

List<Model> items = new ()
{
new Model() { Id = 1, Value = "Value1" },
new Model() { Id = 2, Value = "Value2" }
};

string json = JsonSerializer.Serialize(items);

await db.StringSetAsync("my-key", json);

--

--

Sasha Marfut
Geek Culture

1 million+ views on Medium | .NET, Design Patterns, Architecture, API