Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can StackExchange.Redis be used to store POCO?

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?

like image 858
SomeGuyWhoCodes Avatar asked Jan 09 '15 09:01

SomeGuyWhoCodes


1 Answers

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);
    }
}
like image 178
Frank Avatar answered Sep 18 '22 06:09

Frank