【问题标题】:How to check if the key exists in Redis?如何检查密钥是否存在于 Redis 中?
【发布时间】:2020-08-19 21:36:20
【问题描述】:

我在 Laravel 模型中有一个函数,我需要检查我的键($key 变量)是否存在于 Redis 中,换句话说,我想创建一个条件,不允许来自 redis 的重复结果。这是我的功能。任何帮助表示赞赏。

功能

public static function cacheFields($fields)
{
    foreach ($fields as $fieldname => $values) {

        $key = static::$redisFieldKey.$fieldname; // here is that variable

        Redis::pipeline(function ($pipe) use ($key, $values) {
            foreach ($values as $value => $label) {
                $pipe->hset($key, $value, $label);
            }
        });
    }
}

【问题讨论】:

  • 复制哪一部分?哈希和哈希键是唯一的
  • $key = static::$redisFieldKey.$fieldname;我遇到过有时会重复

标签: php laravel redis


【解决方案1】:

当您对不存在的键执行hset 时,它将set 您的哈希与字段及其对应的值。当您针对现有哈希(和字段键)执行它时,它将update 现有哈希字段的哈希值。

127.0.0.1:6379> hset myhash myhashfield myvalue
(integer) 1
127.0.0.1:6379> hgetall myhash
1) "myhashfield"
2) "myvalue"
127.0.0.1:6379> hset myhash myhashfield anothervalue
(integer) 0
127.0.0.1:6379> hgetall myhash
1) "myhashfield"
2) "anothervalue"
127.0.0.1:6379>

如果你想检查密钥是否存在,你可以使用exists O(1)

127.0.0.1:6379> exists myhash
(integer) 1
127.0.0.1:6379> exists nonexisting
(integer) 0

如果要检查hash字段是否存在,可以使用hexistsO(1)

127.0.0.1:6379> hexists myhash myhashfield
(integer) 1
127.0.0.1:6379> hexists myhash nonfield
(integer) 0
127.0.0.1:6379> hexists notmyhash myfield
(integer) 0

编辑:

documentation 声明 hset;

将存储在 key 的 hash 中的字段设置为 value。如果 key 不存在,则创建一个包含哈希的新 key。如果字段已存在于哈希中,则将其覆盖。

【讨论】:

    猜你喜欢
    • 2016-05-14
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 2013-07-03
    • 2017-05-04
    相关资源
    最近更新 更多