X

Redis for .NET Developer – Redis String Datatype part 2

Redis

Continuing on with our Redis for .NET Developer, the Redis String Datatype is also used to store integers, float and other utility commands to manipulate strings.

Redis String Datatype using Integers

In Redis float and integers are represented by string. Redis parses the string value as an integer and the neat thing about them is when you do operations on strings they are atomic. When there are multiple clients issuing INCR against the same key, it will never enter into a race condition.

  • INCR key : Increment the value by one O(1)
  • INCRBY key value: Increments the value by the given value (integer) O(1)
  • DECR key: Decrements the value by one O(1)
  • DECRBY key value: Decrements the value by the given value (integer) O(1)
  • APPEND key value: Concatenate the existing integer with the new integer O(1)
  • INCRBYFLOAT key value : Increment the float value by given value (float) O(1)

C# Code using integer and float

var number = 101;
var intKey = "intKey";

if (redis.StringSet(intKey, number))
{
     //redis incr command
     var result = redis.StringIncrement(intKey); //after operation Our int number is now 102
     Console.WriteLine(result);

     //incrby command
     var newNumber = redis.StringIncrement(intKey, 100); // we now have incremented by 100, thus the new number is 202
     Console.WriteLine(newNumber);               

     redis.KeyDelete("zeroValueKey");
     //by default redis stores a value of zero if no value is provided           
     var zeroValue = (int)redis.StringGet("zeroValueKey");
     Console.WriteLine(zeroValue);

     var someValue = (int)redis.StringIncrement("zeroValueKey"); //someValue is now 1 since it was incremented
     Console.WriteLine(someValue);
                
     //decr command
     redis.StringDecrement("zeroValueKey");
     someValue = (int)redis.StringGet("zeroValueKey"); //now someValue is back to 0   
     Console.WriteLine(someValue);

     //decrby command
     someValue = (int)redis.StringDecrement("zeroValueKey", 99); // now someValue is -99   
     Console.WriteLine(someValue);
                
     //append command
     redis.StringAppend("zeroValueKey", 1);
     someValue = (int)redis.StringGet("zeroValueKey"); //"Our zeroValueKey number is now -991   
     Console.WriteLine(someValue);

     redis.StringSet("floatValue", 1.1);
     var floatValue = (float)redis.StringIncrement("floatValue", 0.1); //fload value is now 1.2   
     Console.WriteLine(floatValue);
}

For source code please visit
https://github.com/taswar/RedisForNetDevelopers/tree/master/3.RedisStringsAsInt

For our next blog post, I will cover more functionality and other datatype in Redis.

For previous Redis topics

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