Search code examples
c#redisstackexchange.redis

Redis KeyExists then GetValue Optimization


I'm new to using Redis and have written my c# block to be:

public string GetValue(string key) 
{
    if (IDatabase.KeyExists(key))
    {
        return IDatabase.StringGet(key);
    }
    else 
    {
        //Get value from SQL, put it into Redis, then return it
    }
}

My question is, how inefficient is it that I am first checking Redis for existance of the key, and then asking Redis a second time for the value of that key? Essentially I'm making two trips to Redis here and I want to know if that's negligible given Redis' speed, or is that something I should try to change in my repo layer so that only a single trip to Redis gets made?


Solution

  • Actually Redis throws errors for very edge cases, and trying to get a string key value using StackExchange.Redis won't throw an exception if the key doesn't exist.

    Since you're using StackExchange.Redis to work with Redis, when you call IDatabase.GetString the return value is a RedisValue (it's a struct! it can't be null excepting if it's turned into a nullable type), which has a HasValue property.

    That is, you should get the Redis string as RedisValue (don't cast it to string directly). Your code should look like this:

    public string GetValue(string key) 
    {
        RedisValue value = _cacheRepo.GetString(key);
    
        // You might also use !value.IsNullOrEmpty
        if (!value.IsNull)
        {
            return value;
        }
        else 
        {
            //Get value from SQL, put it into Redis, then return it
        }
    }