17

I am trying to evaluate Redis by using two well known C# drivers ServiceStack and StackExchange. Unfortunately I cannot use ServiceStack because it's not free. Now I'm trying StackExchange.

Does anybody know whether with StackExchange.Redis I can persist POCOs?

Frank
  • 4,461
  • 13
  • 28
SomeGuyWhoCodes
  • 579
  • 6
  • 19

1 Answers1

20

StackExchange.Redis can store Redis Strings, which are binary safe. That means, that you can easily serialize a POCO using the serialization technology of your choice and put it in there.

The following example uses the .NET BinaryFormatter. Please note that you have to decorate your class with the SerializableAttribute to make this work.

Example set operation:

PocoType somePoco = new PocoType { Id = 1, Name = "YouNameIt" };
string key = "myObject1";
byte[] bytes;

using (var stream = new MemoryStream())
{
    new BinaryFormatter().Serialize(stream, somePoco);
    bytes = stream.ToArray();
}

db.StringSet(key, bytes);

Example get operation:

string key = "myObject1";
PocoType somePoco = null;
byte[] bytes = (byte[])db.StringGet(key);

if (bytes != null)
{
    using (var stream = new MemoryStream(bytes))
    {
        somePoco = (PocoType) new BinaryFormatter().Deserialize(stream);
    }
}
Frank
  • 4,461
  • 13
  • 28
  • It is a good example, it please please please don't use BknaryFormatter. Ever. /cc @Duke – Marc Gravell Jan 11 '15 at 14:18
  • 5
    @Frank BF is *terrible* at versioning and refactoring, and is platform-specific. I would strongly recommend something designed for tolerant multi-platform work; xml, json, or for binary: protobuf, etc. – Marc Gravell Jan 11 '15 at 18:17
  • 1
    @MarcGravell Is Newtonsoft.Json is a good alternative for BinaryFormatter? – Burak Karakuş Jan 24 '16 at 10:38
  • 5
    @Burak it is a good and mature serializer, for sure. It depends on your objectives. If you want to minimize bandwidth and server-side impact (CPU, memory), is use something like protobuf-net or bond. If that isn't important: json is fine - it has the advantage of being human readable, at the price of size. – Marc Gravell Jan 24 '16 at 11:15