.NET Core 中的分布式缓存 (Redis)

The*_*Guy 5 c# asp.net-core-mvc asp.net-core

我正在尝试使用 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我假设我需要序列化 ​​json 中的对象然后存储字符串?除非有别的办法。

谢谢你!

Pet*_*esz 6

IDistributedCache 存储 byte[] 且 .Net Core 2.0 支持二进制序列化,因此我认为这将是最有效的存储形式(而不是 JSON)。我还没有使用 Redis 对此进行测试,但它应该可以工作:

Serializable首先向POCO添加属性:

[Serializable]
public class Poco {
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后使用以下命令对其进行序列化BinaryFormatter

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

并荒漠化:

var bytes = cache.get("cache key");
using(var stream = new MemoryStream(bytes)) {
    var model = new BinaryFormatter().Deserialize(stream) as Poco;
}
Run Code Online (Sandbox Code Playgroud)


小智 0

IDistributedCachebyte[]基于的,尽管扩展方法允许您使用字符串,因为它是一个通用接口,旨在支持许多在线协议。因此,您负责序列化您自己的对象。