I need to store a list of data in the cache.
Sometimes I’ll need full list sometimes I’ll only need to query the results and return one item from the list.
Current logic for one item is this:
User result;
var cachedUsers = _cache.Get<List<User>>(Constants.Cache.UsersKey);
if( cachedUsers != null)
{
result = cachedUsers.FirstOrDefault(u => u.UserID == userID);
if (result != null)
return result;
}
result = GetUserFromDb(userID);
if (cachedUsers != null)
{
cachedUsers.Add(result);
_cache.Store(StoreMode.Set, Constants.Cache.UsersKey, cachedUsers);
}
return result;
Can I access one element directly from the cache without loading full list of users? I’d also need to logic to add a user into the cache without loading full list and overwriting it.
EDIT: I have option to store items separate from the list, or write the cache from scratch with different approach.
What is the best way to implement this logic?
The most granular action you can do is to retrieve a particular key. If you store a list of items under that key, you get the list. To get exactly one item, you’ll need to store an item per key.
There are various strategies for this, however note that atomicity is at the key level so doing actions across multiple keys could result in race conditions.
Personally, I would custom serialize your list (instead of relying on default .NET serialization) as this will be fairly quick. But this depends on how many times “sometimes” is when talking about updating individual keys or requesting individual keys. The common sense “store it as you will use it” will apply here.
For the custom serialization, we use Protobuf-net and store the resulting
byte[]into the cache manually – as in, the caches takes and gives abyte[]and we do the serialization manually.