Redis 在获取值之前是否应该检查键是否存在?

问题描述 投票:0回答:1

我正在开发一个遗留项目,Redis 缓存实现将始终检查某个值是否存在,然后再尝试获取或删除它。

例如:

...
    public function get($id): mixed
    {
        try {
            if ($this->connection->exists($id)) {
                return $this->connection->get($id);
            }
        } catch (PredisException $predisException) {
            ...
        }

        return null;
    }
...

这似乎有点过分了。我在网上查过,但似乎在任何地方都找不到这种模式。这是没有必要的并且会影响性能,对吗?

我还没有尝试改变任何东西,因为这是我们项目的核心部分。

caching redis
1个回答
0
投票

是的,这太过分了。它可以(并且应该)简单地更改为:

...
    public function get($id): mixed
    {
        try {
            return $this->connection->get($id);
        } catch (PredisException $predisException) {
            ...
        }
    }
...

根据

catch
块正在执行的操作,可能不再需要从外部返回
null

© www.soinside.com 2019 - 2024. All rights reserved.