Distributed Cache (Redis) in .NET Core

Viewed 2287

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!

3 Answers

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.

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);
Related