您可以使用事务来自动执行 DEL 和 RPUSH 命令。见CLIENT.MULTI([COMMANDS])。
如果您在处理列表时修改了列表,如果您希望事务不执行,您可以为您的密钥添加一个 WATCH。见OPTIMISTIC LOCKS。但在这里,您需要恢复/重试逻辑以防万一失败。
要使用WATCH,您首先开始观看,然后使用LRANGE 阅读列表,进行操作,然后进行MULTI、DEL、RPUSH、EXEC。如果在WATCH 和EXEC 之间修改列表,EXEC 将失败。
client.watch(key, function( err ){
if(err) throw err;
client.lrange(key, 0, -1, function(err, result) {
if(err) throw err;
// Process the result
client.multi()
.del(key)
.rpush(key, newItems)
.exec(function(err, results) {
/**
* If err is null, it means Redis successfully attempted
* the operation.
*/
if(err) throw err;
/**
* If results === null, it means that a concurrent client
* changed the key while we were processing it and thus
* the execution of the MULTI command was not performed.
*
* NOTICE: Failing an execution of MULTI is not considered
* an error. So you will have err === null and results === null
*/
});
});
});
Redis 中的RPUSH 一次支持多个元素。考虑通过直接使用[send_command][3]、ES6 spread syntax 或直接传递数组来一次推送多个元素(取决于您运行的版本)。
也就是说,考虑使用 Lua 脚本。这里有点推动你开始:
EVAL "local list1 = redis.call('LRANGE', KEYS[1], 0, -1) for ix,elm in ipairs(list1) do list1[ix] = string.gsub(elm, 'node', 'nodejs') end redis.call('DEL', KEYS[1]) redis.call('RPUSH', KEYS[1], unpack(list1)) return list1" 1 myList
这里是 Lua 脚本的友好视图:
local list1 = redis.call('LRANGE', KEYS[1], 0, -1)
for ix,elm in ipairs(list1) do
list1[ix] = string.gsub(elm, 'node', 'nodejs')
end
redis.call('DEL', KEYS[1])
redis.call('RPUSH', KEYS[1], unpack(list1))
return list1
这只是在列表的所有元素中将node 替换为nodejs。在String Library Tutorial 上查看有关字符串操作的更多信息。