Working with Redis in C#.NET

Introduction to Redis

Redis (REmote DIctionay Server) is a very popular open-source key-value data store.It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with radius queries. Redis is well known for high performance, flexibility, provides a rich set of data structures, and a simple straightforward API.

Working with Redis in C#.NET

For working with Redis in C#.NET we have a good library StackExchange.Redis. It is a high performance general purpose redis client. It can be installed using Nuget package manager. After installing, we can use the following code to get or set the values
string connectionString="localhost";
ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(connectionString);

IDatabase redis= connection.GetDatabase();

// Write to Redis
redis.StringSet("key", "value"))

// Read from Redis
var val = redis.StringGet("key");
Console.WriteLine(val);

For better modulation of Redis it is recommended to store ConnectionMultiplexer as a static lazy loaded singleton in your application.
public class RedisHelper
{
    public static string connectionString ="localhost";

    private static Lazy lazyConnection = new Lazy(() =>
    {
        ConfigurationOptions redisConfigOptions = ConfigurationOptions.Parse(connectionString);
        redisConfigOptions.ConnectRetry = 10;
        redisConfigOptions.ConnectTimeout = 30000;
        redisConfigOptions.KeepAlive = 60;
        redisConfigOptions.SyncTimeout = 30000;
        return ConnectionMultiplexer.Connect(redisConfigOptions);
    });

    public static ConnectionMultiplexer Connection
    {
        get
        {                      
            return lazyConnection.Value;
        }
    }
}

IDatabase redis = RedisHelper.Connection.GetDatabase();

// Write to Redis
redis.StringSet("key", "value"))

// Read from Redis
var val = redis.StringGet("key");
Console.WriteLine(val);
We can also use the StringSetAsync, StringGetAsync functions for asynchronous programming.

Connecting to a particular Database

In Redis instance we can have multiple database named as db1,db2,db3 etc. So we can connect to a particular database as 
IDatabase redis = RedisHelper.Connection.GetDatabase(dbNumber);

Working with Hashes

Redis Hashes are maps between string fields and string values, so they are the perfect data type to represent objects. While Hashes are used mainly to represent objects, they are capable of storing many elements, so you can use Hashes for many other tasks as well.  

Exmaple: HMSET user:1000 username antirez password P1pp0 age 34

In the above example
  • user:1000 is hashmap name. 
  • username, password, age are the keys and antirez,P1pp0,34 are the values for the respective keys in the hashmap.
We can create hashmap, using the following methods
// To Add the key,value pair to hashmap
IDatabase cache = RedisConnection.Connection.GetDatabase();
await cache.HashSetAsync(hashMapName, key, value);
Note: HashSetAsync will create the hashmap if it doesn't exits.

We can get the value from the hashmap with key as follows
// To retrive the key value from hashmap
IDatabase cache = RedisConnection.Connection.GetDatabase();
string value= await cache.HashGetAsync(hashMapName, key);
Following are the other useful methods for hashmaps
// HashGetAll -- Gets all the items in the hashMap
var allHash = redis.HashGetAll(hashMapName);
foreach (var item in allHash)
{
Console.WriteLine($"Key: {item.Name}, Value:{item.Value});
}

// HashValues -- Gets all the values in the hashMap
var values = redis.HashValues(hashMapName);
foreach (var value in values)
{
 Console.WriteLine(value);
}

// HashKeys -- Gets all the keys in the hashMap
var keys = redis.HashKeys(hashMapName);
foreach (var key in keys)
{
 Console.WriteLine(key);
}

// HashLength -- Gets the length of the hashMap
var len = redis.HashLength(hashMapName);  

// HashExists -- Checks whether the key exists in the hashMap or not
if (redis.HashExists(hashMapName, key))
{
 var item = redis.HashGet(hashMapName, key);
}
Happy Coding! 😊

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment