Reputation: 12525
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!
Upvotes: 5
Views: 4495
Reputation: 181
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);
Upvotes: 2
Reputation: 3396
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;
}
Upvotes: 6
Reputation: 3342
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.
Upvotes: 0