X

Redis for .NET Developer – String Datatype

Redis

Continuing our series on Redis for .NET Developer, we will be looking into the basic string datatype that Redis provides. First to be clear, Redis is more than just a string cache or to store your serialized objects, it is a data structure server, but nevertheless the basic understanding of using strings in Redis will help us learn the foundation of using Redis.

Strings Data Type

String types are the basic data types in Redis. Strings in Redis can store integers, images, files, strings and serialized objects, since Redis strings are byte arrays that are binary safe and have a maximum size of 512MB.

Sets and Gets

The getters and setters are the basic commands that one can use to set or get values in Redis. For single key-value there are GET, SET, SETNX, GETSET

  • GET key: This key gets the value O(1)
  • SET key “value”: This key sets a value for a key O(1)
  • SETNX key “value”: If key does Not eXist this will sets a value against it O(1)
  • GETSET key “value”: Get the old value and sets a new value O(1)

For multi key-value there are MGET, MSET, MSETNX

  • MGET key1 key2: Gets all the corresponding values of keys O(N)
  • MSET key1 “value1” key2 “value2”: Atomic operation, so all given keys are set at once O(N)
  • MSETNX key1 “value1” key2 “value2”: Sets the given keys to their respective values if Not eXist O(N)

Example of using single key-value in C#

Below is an example of single key-value using C# StackExchange.Redis

var redis = RedisStore.RedisCache;

var key = "testKey";
           
if(redis.StringSet(key, "testValue"))
{
   var val = redis.StringGet(key);

   //output - StringGet(testKey) value is testValue
   Console.WriteLine("StringGet({0}) value is {1}", key, val);

   var v1 = redis.StringGetSet(key, "testValue2");

   //output - StringGetSet(testKey) testValue == testValue
   Console.WriteLine("StringGetSet({0}) {1} == {2}", key, val, v1);

   val = redis.StringGet(key);

   //output - StringGet(testKey) value is testValue2
   Console.WriteLine("StringGet({0}) value is {1}", key, val);

   //using SETNX 
   //code never goes into if since key already exist
   if (redis.StringSet(key, "someValue", TimeSpan.MaxValue, When.NotExists))
   {
      val = redis.StringGet(key);
      Console.WriteLine("StringGet({0}) value is {1}", key, val);
   }
   else
   {
      //always goes here
      Console.WriteLine("Value already exist");
   }

   var key2 = key + "1";
   if (redis.StringSet(key2, "someValue", TimeSpan.MaxValue, When.NotExists))
   {
      val = redis.StringGet(key2);
      //output - StringGet(testKey2) value is someValue", key2, val
      Console.WriteLine("StringGet({0}) value is {1}", key2, val);
   }
   else
   {
      //never goes here
      Console.WriteLine("Value already exist");
   }
}       

Example of using multiple key-value in C#

Below is an example of multi key-value using C# StackExchange.Redis

//mset and msetnx
KeyValuePair[] values = {
   new KeyValuePair("a", "x"),
   new KeyValuePair("b", "y")
};

if (redis.StringSet(values))
{
   RedisKey[] myKeys = {"b", "a"};
   var allValues = redis.StringGet(myKeys);

   //output - y,x
   Console.WriteLine(string.Join(",", allValues));                
}                  

Serialization of objects into Redis with C#

One can use Json.NET serialization of a C# object into Redis. There is also a StackExchange.Redis.Extensions Nuget package that allows one to serialize objects with protobuf, jil, etc. For more details please look at https://github.com/imperugo/StackExchange.Redis.Extensions.
In the example below we will Newton.Json to serialize a User C# object

 //serialization of object
User u = new User {Name = "taswar", Twitter = "@taswarbhatti"};

var userKey = "user:taswar";
var serializedUser = JsonConvert.SerializeObject(u);
redis.StringSet(userKey, serializedUser);           

var u2 = JsonConvert.DeserializeObject(redis.StringGet(userKey));

//output Name = taswar, Twitter = @taswarbhatti
Console.WriteLine("Name = {0}, Twitter = {1}", u2.Name, u2.Twitter);

For our next blog post, I will cover other functionality that the string datatype has in Redis, and also how Redis can treat strings as integer also.

For source code please visit
https://github.com/taswar/RedisForNetDevelopers/tree/master/2.RedisString

For previous Redis topics

  1. Intro to Redis for .NET Developers
  2. Redis for .NET Developer – Connecting with C#
Categories: .NET Redis
Taswar Bhatti:
Related Post