Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 352
JBStevens6 Avatar asked May 05 '15 18:05

JBStevens6


1 Answers

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.HasValue)
    {
        return value;
    }
    else 
    {
        //Get value from SQL, put it into Redis, then return it
    }
}
like image 193
Matías Fidemraizer Avatar answered Oct 21 '22 08:10

Matías Fidemraizer