Skip to content

Serialization

Andrey Bulygin edited this page May 21, 2013 · 1 revision

Home

Redis data serializer

Each instance of RedisClient has a reference to serializer. As a default serializer RedisBoost uses RedisClient.DefaultSerialzier.

There is a default implementation that uses System.Runtime.Serialization.DataContractSerializer to serialze complex objects. Primitive types, such as numeric types, strings, Guid, DateTime are first represented as strings and then serialized to byte[].

Also you can create your own implementation of serializer. All you need is to create a class with BasicRedisSerializer as a parent and override some methods. There will be an example soon.

// creates redis client with default implementation of serializer (RedisClient.DefaultSerialzier)
var redisClient = await RedisClient.ConnectAsync("127.0.0.1",6379);

// you can setup your own serializer as a default
RedisClient.DefaultSerialzier = mySerializer;
var redisClient = await RedisClient.ConnectAsync("127.0.0.1",6379); // this instance will use mySerializer

// or you can pass serializer while creating redis client
var redisClient = await RedisClient.ConnectAsync("127.0.0.1",6379,serializer: mySerialzier); // this instance will use mySerializer

Serialization of commands parameters

Redis commands that demands data to be passed as command parameter has several overloads in RedisClient.

  • First overload takes byte[] as a parameter
  • Second overload takes generic parameter, that will be serialized to byte[]
cli.SetAsync("Key", new byte[]{1,2,3}).Wait();
cli.SetAsync("Key2", new MyObject()).Wait(); // second parameter will be serialized to byte array

Bulk and MultiBulk responses

Some Redis commands return bulk or multi-bulk responses (http://redis.io/topics/protocol). In this case RedisBoost returns instanses of Bulk or MultiBulk classes.

Bulk could be implicitly converted to byte[]. MultiBulk could be implicitly converted to byte[][]. Both classes have IsNull property to check whether response is bulk (multi-bulk) null. If you try to implicitly convert null response to byte[] or byte[][] null will be returned, and any other operation would generate RedisException.

Also any Redis response could be deserialized to the type you want.

// bulk reply examples
byte[] result = cli.GetAsync("Key").Result; //implicit conversion to byte[]
string result = cli.GetAsync("Key").Result.As<string>(); //deserialization to specified type

// multi-bulk reply examples
byte[][] result = cli.MGetAsync("Key", "Key2").Result; //implicit conversion to byte[][];
string[] result = cli.MGetAsync("Key", "Key2").Result.AsArray<string>(); //deserialization to array of specified types

// each part of multi-bulk reply could be treated separately
var multiBulk = cli.MGetAsync("Key", "Key2").Result;
byte[] firstPart = multiBulk[0];//implicit conversion to byte[]
var secondPart = multiBulk[1].As<MyObject>();//deserialization to specified type
Clone this wiki locally