@user_script:1: WRONGTYPE 操作对一个保存错误类型的值的键进行操作

以下是我的 Lua 脚本

if redis.call('sismember',KEYS[1],ARGV[1])==1
then redis.call('srem',KEYS[1],ARGV[1])
else return 0
end
store = tonumber(redis.call('hget',KEYS[2],'capacity'))
store = store + 1
redis.call('hset',KEYS[2],'capacity',store)
return 1

当我在 Java 中运行这个脚本时,会抛出如下异常:

@user_script:1: WRONGTYPE Operation against a key holding the wrong kind of value

Java 代码如下:

Object ojb = jedis.evalsha(sha,2,userName.getBytes(),
                id.getBytes(),id.getBytes()) ;

其中,我的代码中的 userName 是 "tau",id 是 "002",我通过以下方式测试它们的类型:

127.0.0.1:6379> type tau
set
127.0.0.1:6379> type 002
hash

实际上,它们的内容是:

127.0.0.1:6379> hgetall 002
name
"数据来源于数据库核心"
teacher
"taochq"
capacity
54
127.0.0.1:6379> smembers tau
002
004
001
127.0.0.1:6379>

我很困惑,不知道错在哪里,请能帮忙的朋友给予帮助,感激不尽。

点赞
用户3160475
用户3160475

错误信息非常详细 - 你试图在错误类型的键上执行操作。

在你的脚本旁边运行MONITOR命令,然后你就能够轻松地发现错误了。

2020-02-13 16:59:54
用户7017466
用户7017466

尝试运行你的脚本:

EVAL "if redis.call('sismember',KEYS[1],ARGV[1])==1 \n then redis.call('srem',KEYS[1],ARGV[1]) \n else return 0 \n end \n local store = tonumber(redis.call('hget',KEYS[2],'capacity')) \n store = store + 1 \n redis.call('hset',KEYS[2],'capacity',store) \n return 1" 2 tau 002 002

你会看到它是否正常工作。很可能,userName.getBytes()id.getBytes() 并不返回你预期的结果。像 Itamar 建议的那样使用 MONITOR 以查看实际到达服务器的内容。

你将会得到另一个问题: Script attempted to create global variable 'store'。在第五行中添加 local:

local store = tonumber(redis.call('hget',KEYS[2],'capacity'))
2020-02-13 18:26:00