First, a link to the library: ServiceStack.Redis
Now, I want to store objects of type T
where T contains fields Key
and Value
. (for this example)
The issue is that it seems like I can only store strings as both keys and values. As far as a string key, thats perfectly fine, but I need to store an object as the value.
Attached is my code which supports to map Hash -> 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..
}
}
Im aware that I can just JSON stringify my objects but it seems like this just consumes a very much needed performance and losing the effect of good-fast cache memory.
Ill explain what I want to achieve. Lets say I have a group and peoples in it. The group has an Id and each entity inside this group also has an Id. I want to be able to get a specific person from a specific group.
In C# its equivilant of doing Dictionary<string, Dictionary<string, T>>
答案 0 :(得分:2)
您应该将值对象序列化为字符串。在Redis中没有存储对象的概念,当ServiceStack.Redis为其提供Typed API时,它只需将后台的对象序列化为JSON并将JSON字符串发送到Redis的。
ServiceStack.Redis还提供了StoreAsHash(T)
和SetRangeInHash
等API,其中对象属性存储在Redis Hash中,但是在这种情况下,您需要存储嵌套的Hash,以便值可以&# 39;是另一个Redis Hash。
你可以允许另一个&#34;嵌套词典&#34;通过将对象保存在将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);
}