Redis报错:WRONGTYPE Operation against a key holding the wrong kind of value

本文详细解析了在使用Redis时常见的WRONGTYPE错误,通过实例对比了字符串与hash操作的区别,指导如何正确设置与获取数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

记得之前在刚开始使用redis的时候,犯了一个错误,出现WRONGTYPE Operation against a key holding the wrong kind of value的报错,原来是因为我的key出现了问题。原本key是作为字符串的key,我又作为hash的key,当我将字符串的key当hash的key查找时出现了冲突,下面记录一下:

可能文字描述不太直观,那就上份代码:

比如我设置<key,value>,在取用的时候使用opsForValue,那就是错误的

下面是错误的使用


@Autowired
StringRedisTemplate stringRedisTemplate;

stringRedisTemplate.opsForSet().add(key, value);
stringRedisTemplate.expire(key, 100, TimeUnit.MINUTES);
//上下搭配是错误的
if (stringRedisTemplate.hasKey(key)) {
    value = stringRedisTemplate.opsForValue().get(key);
}

来两个正确的

@Autowired
StringRedisTemplate stringRedisTemplate;

//写法一
stringRedisTemplate.opsForValue().set(key, value, 100, TimeUnit.MINUTES);
if (stringRedisTemplate.hasKey(key)) {
    value = stringRedisTemplate.opsForValue().get(key);
}


//写法二
stringRedisTemplate.opsForSet().add(key, value);
stringRedisTemplate.expire(key, 100, TimeUnit.MINUTES);

tringRedisTemplate.opsForSet().members(key);//根据key获取set集合


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值