5

I am trying to setup Distributed Cache in .NET Core using Redis.

I am able to get it implemented but I am having trouble figuring out how to store POCO objects.

In every example I've seen they are storing and retrieving strings. What about more complex data types:

public async Task<string> Get()
{
    var cacheKey = "TheTime";
    var existingTime = _distributedCache.GetString(cacheKey);
    if (!string.IsNullOrEmpty(existingTime))
    {
        return "Fetched from cache : " + existingTime;
    }
    else
    {
        existingTime = DateTime.UtcNow.ToString();
        _distributedCache.SetString(cacheKey, existingTime);
        return "Added to cache : " + existingTime;
    }
}

I assume I'll need to serialize the objects in json then store the strings? Unless there is another way.

Thank you!

1
  • 3
    I came to the same conclusion. We need to serialize the object as json! Commented Nov 26, 2017 at 3:25

3 Answers 3

6

IDistributedCache stores byte[] and .Net Core 2.0 supports binary serialization so I imagine this would be the most efficient form of storage (instead of JSON). I haven't tested this with Redis but it should work:

First add the Serializable attribute to the POCO:

[Serializable]
public class Poco {
    ...
}

Then to serialize it use the BinaryFormatter:

using(var stream = new MemoryStream()) {
    new BinaryFormatter().Serialize(stream, model);
    var bytes = stream.ToArray();
    cache.Set("cache key", bytes);
}

And to deseralize:

var bytes = cache.get("cache key");
using(var stream = new MemoryStream(bytes)) {
    var model = new BinaryFormatter().Deserialize(stream) as Poco;
}
Sign up to request clarification or add additional context in comments.

Comments

2

Setting cache:

var serializedPoco = JsonConvert.SerializeObject(poco);
var  encodedPoco = Encoding.UTF8.GetBytes(serializedPoco);
await distributedCache.SetAsync(cacheKey, encodedPoco, options);

Getting cache:

var encodedPoco = await distributedCache.GetAsync(cacheKey); 
var serializedPoco = Encoding.UTF8.GetString(encodedPoco);

//change the type according to the poco object you are using 
var poco = JsonConvert.DeserializeObject<typeof(Poco)>(serializedPoco);

Comments

0

IDistributedCache is byte[] based, although extension methods allow you to use strings, because it is a generic interface designed to support many over-the-wire protocols. As a result, you are responsible for serializing your own objects.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.