3

I am using azure redis cache and StackExchange.redis client to access it. I am trying to figure out what is the best way to update dictionary values in redis.

public async Task<T> FetchAndCacheAsync<T>(string key, Func<Task<T>> retrieveData, TimeSpan absoluteExpiry)
        {
            T value;

            var output = await _cache.StringGetAsync(key);
            if (output.HasValue)
            {
                value = _serializer.Deserialize<T>(output);
            }
            else
            {
                value = await retrieveData();
                await _cache.StringSetAsync(key, _serializer.Serialize(value), absoluteExpiry);
            }

            return value;
        }

_cache in the above code snippet is of type StackExchange.Redis.IDatabase.

On initialization I store the dictionary object as

FetchAndCacheAsync("diagnostics", () => new Dictionary());

I have a function that will be called frequently to update the DateTime for a given key in the dictionary object.

Question: With my basic knowledge of redis cache I can only think of the following way to update a particular key value of a dictionary stored in a redis cache.

var diagnostics = FetchAndCacheAsync("diagnostics", () => new Dictionary<Guid, DateTime>());

diagnostics[key] = value;
_cache.KeyDeleteAsync("diagnostics");

FetchAndCacheAsync("diagnostics", () => diagnostics);

But it doesn't seem right to me. I am sure there must be a better way to do this. Any suggestion?

1
  • @MarcGravell Would really appreciate your insights on this one. Thanks. Commented May 12, 2015 at 2:42

1 Answer 1

4

Have you looked at the Hash data structure supported by Redis?

http://redis.io/topics/data-types-intro#hashes

IDatabase.HashGet("diagnostics", "MyKey");

IDatabase.HashSet("diagnostics", "MyKey", "My Value");

Sign up to request clarification or add additional context in comments.

1 Comment

I like this approach. Although having problems retrieving all the hash fields and values. Posting a separate question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.