【问题标题】:Redis hasKey method return NULLRedis hasKey 方法返回 NULL
【发布时间】:2021-12-30 02:18:18
【问题描述】:

redis hasKey方法什么时候可以返回null?我已经看到,如果我们在方法参数中也传递 null ,它会返回 false 。那么是否有任何情况下该方法可以返回 null ?

【问题讨论】:

    标签: spring spring-boot redis spring-data-redis


    【解决方案1】:

    如果使用spring data redis,主要包括以下几种情况

    1. 密钥不存在;
    2. 流水线后;
    3. 事务执行后

    你可以看看底层实现org. Springframework. Data. Redis. Connection. Jedis. Jediskeycommands #exists (byte []...)。详情如下:

        @Override
        public Boolean hasKey(K key) {
            byte[] rawKey = rawKey(key);
            return execute(connection -> connection.exists(rawKey), true);
        }
    
       @Nullable
        @Override
        public Long exists(byte[]... keys) {
    
            Assert.notNull(keys, "Keys must not be null!");
            Assert.noNullElements(keys, "Keys must not contain null elements!");
    
            try {
                if (**isPipelined**()) {
                    pipeline(connection.newJedisResult(connection.getRequiredPipeline().exists(keys)));
                    return **null**;
                }
                if (**isQueueing**()) {
                    transaction(connection.newJedisResult(connection.getRequiredTransaction().exists(keys)));
                    return **null**;
                }
                return connection.getJedis().exists(keys);
            } catch (Exception ex) {
                throw connection.convertJedisAccessException(ex);
            }
        }
    
    

    【讨论】:

    • 你能解释一下你提到的 3 件事吗,因为我从 junit 测试过,如果我将 null 传递给 haskey 方法,那么也会返回 false。
    • 其实你的问题符合场景一,你的keynull在redis中可能已经不存在了
    猜你喜欢
    • 2022-12-29
    • 2019-02-05
    • 2015-11-28
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多