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

Example of using multiple key-value in C#

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

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

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#