【问题标题】:C# ServiceStack.Redis store objects in hashmapC# ServiceStack.Redis 在 hashmap 中存储对象
【发布时间】:2017-05-16 09:22:16
【问题描述】:

首先,图书馆的链接:ServiceStack.Redis

现在,我想存储 T 类型的对象,其中 T 包含字段 KeyValue。 (本例)

问题是我似乎只能将字符串存储为键和值。 至于字符串键,那很好,但我需要存储一个对象作为值。

附上我的代码,它支持映射哈希 -> KeyValuePair items

public void PutDictionary(string hashKey, Dictionary<string, T> items, TimeSpan expiration)
{
    try
    {
        using (var trans = _client.CreateTransaction())
        {
            foreach (KeyValuePair<string, T> item in items)
            {
                trans.QueueCommand(r => r.SetEntryInHash(hashKey, item.Key, ???));
            }

            trans.Commit();
        }
    }
    catch (Exception e)
    {
        // some logic here..
    }
}

我知道我可以只对我的对象进行 JSON 字符串化,但这似乎只是消耗了非常需要的性能并失去了快速缓存内存的效果。

我会解释我想要实现的目标。 可以说我有一个团体和人民。 该组有一个 Id,该组内的每个实体也有一个 Id。 我希望能够从特定组中获得特定的人。

在 C# 中,它相当于 Dictionary&lt;string, Dictionary&lt;string, T&gt;&gt;

【问题讨论】:

    标签: c# caching redis servicestack servicestack.redis


    【解决方案1】:

    您应该将值对象序列化为字符串。没有在 Redis 中存储对象的概念,当 ServiceStack.Redis 提供带有 Typed Redis Client 的 Typed API 时,它只是将幕后的对象序列化为 JSON 并将 JSON 字符串发送到 Redis。

    ServiceStack.Redis 还提供了像 StoreAsHash(T)SetRangeInHash 这样的 API,其中对象属性存储在 Redis 哈希中,但是在这种情况下,您存储的是嵌套哈希,因此值不能是另一个 Redis 哈希。

    您可以通过将对象保存在将 hashKey 与 Dictionary 键组合的自定义键处来允许另一个“嵌套字典”,例如:

    foreach (var entry in items) {
        var cacheKey = hashKey + ":" + entry.Key;
        var mapValues = entry.Value.ToJson()
            .FromJson<Dictionary<string,string>>();
        redis.SetRangeInHash(cacheKey, mapValues);
    }
    

    【讨论】:

    • 你能解释一下你的第二行是做什么的吗?它取值,将其转换为字符串,然后做什么?你写的是添加键还是只是覆盖整个哈希?
    • @OriRefael 将其转换为字符串 Dictionary
    • 是的,我完全昏迷了……非常感谢。另外,如果可以的话,还有奖金,有没有办法在同一个请求中设置集合的到期时间?我的意思是,我还没有尝试过,但我确定我必须在这里使用事务
    • @OriRefael no Redis 不允许在同一个哈希请求中设置过期,您需要在之后使密钥过期。
    • 即使我为此使用事务?
    猜你喜欢
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2023-03-25
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多