C# ServiceStack.Redis 在 hashmap 中存储对象
C# ServiceStack.Redis store objects in hashmap
首先,link到图书馆:ServiceStack.Redis
现在,我想存储 T
类型的对象,其中 T 包含字段 Key
和 Value
。 (对于这个例子)
问题是我似乎只能将字符串存储为键和值。
至于字符串键,那很好,但我需要存储一个对象作为值。
附件是我的代码,它支持映射哈希 -> KeyValuePair
项
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<string, Dictionary<string, T>>
您应该将值对象序列化为字符串。在 Redis 中没有存储对象的概念,当 ServiceStack.Redis 提供带有类型化 Redis 客户端的类型化 API 时,它只是在幕后将对象序列化到 JSON 并发送 JSON字符串到 Redis。
ServiceStack.Redis 还提供了 API,例如 StoreAsHash(T)
和 SetRangeInHash
,其中对象属性存储在 Redis 哈希中,但是在这种情况下,您存储的是嵌套哈希,因此值不能是另一个 Redis 哈希。
您可以允许另一个 "nested Dictionary",方法是将对象保存在结合了 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);
}
首先,link到图书馆:ServiceStack.Redis
现在,我想存储 T
类型的对象,其中 T 包含字段 Key
和 Value
。 (对于这个例子)
问题是我似乎只能将字符串存储为键和值。 至于字符串键,那很好,但我需要存储一个对象作为值。
附件是我的代码,它支持映射哈希 -> KeyValuePair
项
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<string, Dictionary<string, T>>
您应该将值对象序列化为字符串。在 Redis 中没有存储对象的概念,当 ServiceStack.Redis 提供带有类型化 Redis 客户端的类型化 API 时,它只是在幕后将对象序列化到 JSON 并发送 JSON字符串到 Redis。
ServiceStack.Redis 还提供了 API,例如 StoreAsHash(T)
和 SetRangeInHash
,其中对象属性存储在 Redis 哈希中,但是在这种情况下,您存储的是嵌套哈希,因此值不能是另一个 Redis 哈希。
您可以允许另一个 "nested Dictionary",方法是将对象保存在结合了 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);
}