Unboxing of ‘redisTemplate.hasKey(xx)’ may produce ‘NullPointerException’的处理

本文探讨了在使用Spring Boot和Java进行Redis操作时,如何处理`redisTemplate.hasKey()`可能导致的`NullPointerException`。IDEA发出警告,提示`Unboxing of redisTemplate.hasKey(key) may produce NullPointerException`。通过分析`hasKey()`和`exists()`的源码,发现`exists()`可能存在返回`null`的情况。为解决这个问题,建议修改代码以避免空指针异常。
摘要由CSDN通过智能技术生成

idea对下边的代码做出了一个提示:

redisTemplate.hasKey(key)

提示说 Unboxing of redisTemplate.hasKey(key)may produce NullPointerException.

网上搜了下,参考了博文Unboxing of ‘stringRedisTemplate.hasKey(xx)‘ may produce ‘NullPointerException‘ 警告_初级码农-CSDN博客

先看下hasKey的代码:

public Boolean hasKey(K key) {
        byte[] rawKey = this.rawKey(key);
        return (Boolean)this.execute((connection) -> {
            return connection.exists(rawKey);
        }, true);
    }

对connection.exists的返回结果做了封装。再看看exist的代码:

@Nullable
    default Boolean exists(byte[] key) {
        Assert.notNull(key, "Key must not be null!");
        Long count = this.exists(key);
        return count != null ? count > 0L : null;
    }

这个返回结果可能是null。因此出现了最开始的问题。

所以把代码改成:

Objects.equals(redisTemplate.hasKey(key)),Boolean.TRUE)

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值