Ori Refael
Ori Refael

Reputation: 3018

C# ServiceStack.Redis store objects in hashmap

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>>

Upvotes: 1

Views: 2398

Answers (1)

mythz
mythz

Reputation: 143319

You should just serialize the value object as a string. There's no concept of storing objects in Redis, when ServiceStack.Redis offers a Typed API with it's Typed Redis Client it's just serializing the object behind the scenes to JSON and sending the JSON string to Redis.

ServiceStack.Redis also provides APIs like StoreAsHash(T) and SetRangeInHash where the objects properties are stored in a Redis Hash, however in this case you're storing a nested Hash so the value can't be another Redis Hash.

You could allow another "nested Dictionary" by saving the object at a custom key that combines hashKey with the Dictionary key, e.g:

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

Upvotes: 2

Related Questions