如果涉及多个redis ops,一般我更喜欢写lua脚本,然后通过我的nodejs程序调用。这是一个不相关的例子,但它展示了如何通过 nodejs 使用 lua。
示例:get_state.lua
local jobId = KEYS[1]
local jobExists = redis.pcall('exists', jobId)
if jobExists == 0 or jobExists == nil then
return 404 -- not found.
end
-- check the job state
local st = tonumber(redis.pcall('hmget', jobId, 'ctlState')[1])
if st == nil then
st = 12002 -- job running, unless explicitly stated otherwise
end
return st
使用 lua 的 NodeJS 代码:比如 index.js
...
// List of script files
var scriptMap = {
getState: {file:'./scripts/get_state.lua'}
};
...
// A function to load the script file to Redis and cache the sha.
function loadScript(script) {
logger.trace("loadScript(): executing...");
if (scriptMap[script]['hash']) {
logger.trace("Sript already loaded. Returning without loading again...");
return Promise.resolve(scriptMap[script]['hash']);
}
//load from file and send to redis
logger.trace("Loading script from file %s...", scriptMap[script].file);
return fs.readFileAsync(scriptMap[script].file).then(function(data) {
return getConnection().then(function(conn) {
logger.trace("Loading script to Redis...");
return conn.scriptAsync('load', data)
})
})
}
最后,还有一个使用缓存的 sha 摘要来执行脚本的函数:
getJobState: function(jobId) {
return loadScript('getState').then(function(hash) {
return getConnection().then(function (conn) {
return conn.evalshaAsync(hash, 1, jobId)
})
})
},