Reputation: 33
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?
Upvotes: 3
Views: 8138
Reputation: 3122
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");
Upvotes: 4