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

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

Redis报错:WRONGTYPE Operation against a key holding the wrong kind of value_第1张图片

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

比如我设置,在取用的时候使用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集合


 

你可能感兴趣的:(Redis报错:WRONGTYPE Operation against a key holding the wrong kind of value)