javascript 如何将javascript数组保存为redis列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19745224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save javascript array as redis list
提问by user2522545
The following code save the whole array as single value in redis list. But I want to save array values individually. How can I do it?
以下代码将整个数组保存为 redis 列表中的单个值。但我想单独保存数组值。我该怎么做?
P.S So sorry for poor English.
PS 很抱歉英语不好。
var redis = require('redis'),
client = redis.createClient();
var arr = [1,2,3];
client.rpush('testlist',arr);
回答by gimenete
Use multi()
to pipeline multiple commands at once:
用于multi()
一次管道化多个命令:
var redis = require('redis'),
client = redis.createClient();
var arr = [1,2,3];
var multi = client.multi()
for (var i=0; i<arr.length; i++) {
multi.rpush('testlist', arr[i]);
}
multi.exec(function(errors, results) {
})
And finally call exec()
to send the commands to redis.
最后调用exec()
将命令发送到redis。
回答by FGRibreau
Even if @gimenete answer works, the best way to do what you want is to forward the list elements as arguments to rpush like so:
即使@gimenete 回答有效,做你想做的最好的方法是将列表元素作为参数转发给 rpush,如下所示:
var redis = require('redis'),
client = redis.createClient();
var arr = [1,2,3];
client.rpush.apply(client, ['testlist'].concat(arr));
// ... or with a callback
client.rpush.apply(client, ['testlist'].concat(arr).concat(function(err, ok){
console.log(err, ok);
}));
Pros: - a single instruction will be transmited to Redis
优点: - 一条指令将被传输到 Redis
Cons:
- a corner-case: .apply
will throw a RangeError: Maximum call stack size exceeded
if the arguments list length passed to rpush is too large (a little over 100 000 items for v8).
缺点: - 一个极端情况:如果传递给 rpush 的参数列表长度太大(v8 的项目超过 100 000 项),.apply
则会抛出 a RangeError: Maximum call stack size exceeded
。
From MDC:
来自 MDC:
The consequences of applying a function with too many arguments (think more than tens of thousands of arguments) vary across engines (JavaScriptCore has hard-coded argument limit of 65536), because the limit (indeed even the nature of any excessively-large-stack behavior) is unspecified. Some engines will throw an exception. More perniciously, others will arbitrarily limit the number of arguments actually passed to the applied function.
应用具有过多参数的函数(想想超过数万个参数)的后果因引擎而异(JavaScriptCore 的硬编码参数限制为 65536),因为限制(实际上甚至任何过大堆栈的性质)行为)未指定。有些引擎会抛出异常。更有害的是,其他人会任意限制实际传递给应用函数的参数数量。