imperugo / StackExchange.Redis.Extensions

MIT License
601 stars 179 forks source link

Differ between 'key does not exist' and 'key exists with default value' in one round trip #589

Open dietermijle opened 3 months ago

dietermijle commented 3 months ago

Is your feature request related to a problem? Please describe. I'm trying to implement the cache aside strategy with negative (null) caching supported.

Currently, there is no way to know if the default value is cached or not in a single round trip. I need to use a combination of the GetAsync & the ExistsAsync method on the ICache to know the difference.

This can cause issues when multiple executions access the cache concurrently. It might occur that the cache is updated (due to another exeuction) in between both calls, resulting in strange behavior.

Describe the solution you'd like It would be nice if there was an option to know the difference between a cache miss (key not found in cache) and a negative cache result (key found in cache with default value) in a single atomic operation.

LeaFrock commented 3 months ago

Cached value is ValueType

It's easy with nullable struct, for example,

int? num = await redisDb.GetAsync<int?>(key);
// null means the value does not exist
// 0 means the value is default

Cached value is RefType

When the value is null, the Redis side normally caches an empty byte array based on the serializer.

A workaround is using the exposed StackExchange.Redis.IDatabase property of IRedisDatabase. For example,

RedisValue str = await redisDb.Database.StringGetAsync(key);
//  If RedisValue.IsNull is true, the value does not exist
//  If not, check whether the value is empty string.
//  Afterwards, if the value is a complex object, you have to deserialize it manually.