Sobes.tech
Junior — Middle

What is the main purpose and application of Redis in projects?

sobes.tech AI

Answer from AI

Redis is a high-performance in-memory data store often used as a cache, message broker, or database supporting data structures (strings, lists, sets, hashes, etc.). The main purpose of Redis in projects is to accelerate access to frequently used data, reduce load on the primary database, and ensure fast message exchange between system components.

An example of using Redis in C# is caching database query results to reduce response time:

// Example of simple caching using StackExchange.Redis
using StackExchange.Redis;

var redis = ConnectionMultiplexer.Connect("localhost");
var db = redis.GetDatabase();

string cacheKey = "user:123";
string cachedUser = db.StringGet(cacheKey);

if (cachedUser == null)
{
    // Get data from DB (conditionally)
    string userData = GetUserFromDatabase(123);
    db.StringSet(cacheKey, userData, TimeSpan.FromMinutes(10));
    cachedUser = userData;
}

Console.WriteLine(cachedUser);

string GetUserFromDatabase(int id) {
    // Placeholder for example
    return "User data from DB";
}