Redis KeyExists 然后GetValue优化

Redis KeyExists then GetValue Optimization

我刚开始使用 Redis,我的 C# 代码块是:

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

我的问题是,我首先检查 Redis 是否存在密钥,然后再次向 Redis 询问该密钥的值,效率有多低?本质上,我在这里进行了两次 Redis 访问,我想知道考虑到 Redis 的速度,这是否可以忽略不计,或者我是否应该尝试在我的回购层中进行更改,以便只进行一次 Redis 访问?

实际上,Redis 会在非常极端的情况下抛出错误,并且尝试使用 StackExchange.Redis 获取字符串键值不会抛出异常,如果该键没有存在。

由于您使用 StackExchange.Redis 与 Redis 一起工作,当您调用 IDatabase.GetString 时,return 值是 RedisValue(它是一个 struct!它不能为 null,除非它变成了可空类型),它有一个 HasValue 属性。

也就是说,你应该得到 Redis 字符串为 RedisValue(不要直接将其转换为 string)。您的代码应如下所示:

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