我需要使用 Redis Lua 脚本调用 Redis HMSET。这是一个 CoffeeScript :
redis = require("redis")
client = redis.createClient();
lua_script = "\n
-- here is the problem\n
local res = redis.call('hmset', KEYS[1],ARGV[1])\n
print (res)\n
-- create secondary indexes\n
--\n
--\n
return 'Success'\n
"
client.on 'ready', () ->
console.log 'Redis is ready'
client.flushall()
client.send_command("script", ["flush"])
args = new Array(3)
args[0] = '1111-1114'
args[1] = 'id'
args[2] = '111'
callback = null
#client.send_command("hmset", args, callback) # this works
client.eval lua_script, 1, args, (err, res) ->
console.log 'Result: ' + res
在 LUA 脚本中调用 HMSET 的正确语法/模式是什么? 顺便说一句——我知道 redis.HMSET 命令。
最佳答案
首先,您确定您在 CoffeeScript Redis 库中正确使用了 eval
吗?您显然传递了三个参数:脚本、键的数量和一个数组。我怀疑这不是它的工作原理。如果这是 node_redis,则数组中必须包含所有内容或不包含任何内容,因此请尝试:
args = new Array(5)
args[0] = lua_script
args[1] = 1
args[2] = '1111-1114'
args[3] = 'id'
args[4] = '111'
callback = null
client.eval args, (err, res) ->
console.log 'Result: ' + res
(可能有更好的语法,但我不知道 CoffeeScript。)
其次,在此示例中,您尝试 HMSET 单个字段/值对:
HMSET lua_script 1111-1114 id 111
实际上你可以在这里用 HSET 替换 HMSET,但让我们先让它工作。
在这一行中:
local res = redis.call('hmset', KEYS[1], ARGV[1])
您只使用两个 参数调用 HMSET,键包含散列和字段。您需要添加作为第二个参数的值:
local res = redis.call('hmset', KEYS[1], ARGV[1], ARGV[2])
这将使您的示例正常工作,但是如果您想像这样实际设置多个 字段(这是 MHSET 的目标)怎么办?
HMSET lua_script 1111-1114 id 111 id2 222
在 CoffeeScript 中你会这样写:
args = new Array(7)
args[0] = lua_script
args[1] = 1
args[2] = '1111-1114'
args[3] = 'id'
args[4] = '111'
args[5] = 'id2'
args[6] = '222'
callback = null
client.eval args, (err, res) ->
console.log 'Result: ' + res
...但是现在 ARGV
中有 四个 元素要传递给 Lua 中的 redis.call
。实际上你必须传递 所有 ARGV
的元素,这叫做 unpack()在 Lua 中:
local res = redis.call('hmset', KEYS[1], unpack(ARGV))
使用 unpack()
的唯一问题是,如果您在 ARGV
中有很多 真实 元素(数千),它可能会损坏因为它会溢出堆栈,在这种情况下,您应该在 Lua 脚本中使用循环在 ARGV
的切片上调用 HMSET,但您现在可能不必担心这个......
关于node.js - 使用 LUA 触发 Redis HMSET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18434009/