【问题标题】:Check value exists and return if it does Jedis Redis检查值是否存在,如果存在则返回 Jedis Redis
【发布时间】:2014-07-24 16:37:51
【问题描述】:

我正在使用 Jedis Redis 客户端,并希望能够确定密钥是否存在,如果存在则获取值。我目前正在使用 if 语句来检查密钥是否存在,如果不存在则返回 null。我假设这不是最好的做事方式,因为您需要多次访问数据库。有没有办法在获取值的同一步骤中检查键是否存在?

一些示例代码:

try {
    if (!jedis.exists(name)) {
        return null;
    }

    return jedis.hgetAll(name);
} catch (JedisConnectionException exception) {
    // Do stuff
} finally {
    // Clean up
}

【问题讨论】:

    标签: java redis jedis


    【解决方案1】:

    使用 Redis,如果存在键,则关联的值不为空。这适用于 set、zset、hash、list,但不适用于 string。

    例子:

    > hmset x id 0
    OK
    > keys *
    1) "x"
    > hdel x id
    (integer) 1
    > keys *
    (empty list or set)
    

    在您的情况下,您只需执行 hgetAll 并检查返回是否为空。

    【讨论】:

    • 为空且不为空?
    猜你喜欢
    • 2016-01-18
    • 2011-12-26
    • 2021-03-26
    • 1970-01-01
    • 2020-02-20
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多