我正在尝试使用Redis在.NET Core中设置分布式缓存。
我能够实现它,但我无法弄清楚如何存储POCO对象。
在每个例子中,我都看到他们正在存储和检索字符串。更复杂的数据类型呢?
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;
}
}
我假设我需要在json中序列化对象然后存储字符串?除非有另一种方式。
谢谢!
答案 0 :(得分:3)
IDistributedCache存储byte []和.Net Core 2.0支持binary serialization所以我想这将是最有效的存储形式(而不是JSON)。我没有用Redis测试过这个,但它应该可以工作:
首先将Serializable
属性添加到POCO:
[Serializable]
public class Poco {
...
}
然后序列化使用BinaryFormatter
:
using(var stream = new MemoryStream()) {
new BinaryFormatter().Serialize(stream, model);
var bytes = stream.ToArray();
cache.Set("cache key", bytes);
}
并且去除deseralize:
var bytes = cache.get("cache key");
using(var stream = new MemoryStream(bytes)) {
var model = new BinaryFormatter().Deserialize(stream) as Poco;
}
答案 1 :(得分:0)
byte[]
基于knex.insert
,虽然扩展方法允许您使用字符串,因为它是一个通用接口,旨在支持许多线上协议。因此,您负责序列化您自己的对象。