Multiple cache keys for single object #305
-
Hello, I would like to ask, how do you solve a scenario in which, you have entity e.g. User(int id, Guid guid, string email, etc...) and it can be fetched via multiple identifiers Id/Guid/Email. I see some options but I do not like either of them, can you steer me in right direction? By the way User's Id/Guid/Email cannot be changed. Option 1: Get it and then set it with different keys
Option 2:
Option 3:
Thank you for help |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Hi @ivann14 sorry for being late, I somehow missed this. In general, if possible, I tend to have only one "canonical" cache entry for each object, in this case the user. In this way an update to a user will be reflected immediately for whatever lookup you'll end up using (via guid, via id or via email), and you'll store in cache only one copy of each user. Something like this: public User GetUserByGuid(Guid guid) {
return cache.GetOrSet<User>($"userByGuid:{guid}",_ => GetFromDbByGuid(guid));
}
public User GetUserById(int id) {
var guid = cache.GetOrSet<Guid>($"userGuidById:{id}",_ => GetFromDbById(id)?.Guid);
return GetUserByGuid(guid); // THIS WILL STILL USE THE CACHE VIA THE GetUserByGuid
}
public User GetUserByEmail(string email) {
var guid = cache.GetOrSet<Guid>($"userGuidByEmail:{email}",_ => GetFromDbByEmail(email)?.Guid);
return GetUserByGuid(guid); // THIS WILL STILL USE THE CACHE VIA THE GetUserByGuid
} Thoughts? Hope this helps. |
Beta Was this translation helpful? Give feedback.
Another thing to consider as a potential optimization is this: