Redis KeyExists then GetValue Optimization

I'm new to using Redis and wrote my C # block:

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 I am that I first check Redis for a key and then ask Redis a second time about the meaning of that key? Basically, I am doing two trips to Redis here and I want to know if this negligible speed of Redis was, or is this something I should try to change in my repo level to only make one trip to Redis?

+3


source to share


1 answer


In fact Redis throws errors for very edge cases and tries to get the string key value using StackExchange.Redis will not throw an exception if the key does not exist.

Since you are using StackExchange.Redis to work with Redis, when you call IDatabase.GetString

, the return value is RedisValue

(it's a struct

! It can't be null, except if it turned into a nullable type) that has a property HasValue

.



That is, you have to get the Redis string as RedisValue

(don't pass it directly to string

). 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
    }
}

      

+7


source







All Articles