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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
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
- Intro to Redis for .NET Developers
- Redis for .NET Developer – Connecting with C#
- Redis for .NET Developer – String Datatype
Leave A Comment