Javascript 如何在javascript中获取redis中的所有键和值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42926990/
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 get all keys and values in redis in javascript?
提问by Bhushan Gadekar
I am creating a node API using javascript. I have used redis as my key value store. I created a redis-client in my app and am able to get values for perticular key.
我正在使用 javascript 创建一个节点 API。我使用 redis 作为我的键值存储。我在我的应用程序中创建了一个 redis 客户端,并且能够获取特定键的值。
I want to retrieve all keys along with their values. So Far I have done this :
我想检索所有键及其值。到目前为止,我已经这样做了:
app.get('/jobs', function (req, res) {
var jobs = [];
client.keys('*', function (err, keys) {
if (err) return console.log(err);
if(keys){
for(var i=0;i<keys.length;i++){
client.get(keys[i], function (error, value) {
if (err) return console.log(err);
var job = {};
job['jobId']=keys[i];
job['data']=value;
jobs.push(job);
});
}
console.log(jobs);
res.json({data:jobs});
}
});
});
but I always get blank array in response.
但我总是得到空白数组作为回应。
is there any way to do this in javascript?
有没有办法在javascript中做到这一点?
Thanks
谢谢
回答by Aruna
First of all, the issue in your question is that, inside the forloop, client.getis invoked with an asynchronouscallback where the synchronousforloop will not wait for the asynchronous callback and hence the next line res.json({data:jobs});is getting called immediately after the forloop before the asynchronous callbacks. At the time of the line res.json({data:jobs});is getting invoked, the array jobsis still empty []and getting returned with the response.
首先,您问题中的问题是,在for循环内部,client.get使用异步回调调用,其中同步for循环不会等待异步回调,因此在异步回调之前的循环之后res.json({data:jobs});立即调用下一行for。在res.json({data:jobs});调用该行时,该数组jobs仍为空[]并与响应一起返回。
To mitigate this, you should use any promise modules like async, bluebird, ES6 Promiseetc.
为了缓解这种情况,您应该使用任何承诺模块,如async,bluebird,ES6 Promise等。
Modified code using asyncmodule,
使用async模块修改代码,
app.get('/jobs', function (req, res) {
var jobs = [];
client.keys('*', function (err, keys) {
if (err) return console.log(err);
if(keys){
async.map(keys, function(key, cb) {
client.get(key, function (error, value) {
if (error) return cb(error);
var job = {};
job['jobId']=key;
job['data']=value;
cb(null, job);
});
}, function (error, results) {
if (error) return console.log(error);
console.log(results);
res.json({data:results});
});
}
});
});
But from the
Redisdocumentation, it is observed that usage of Keys are intended for debugging and special operations, such as changing your keyspace layout and not advisable to production environments.
但是从
Redis文档中可以看出,Keys 的用途是用于调试和特殊操作,例如更改您的键空间布局,不建议用于生产环境。
Hence, I would suggest using another module called redisscanas below which uses SCANinstead of KEYSas suggested in the Redisdocumentation.
因此,我建议使用另一个名为redisscan 的模块,如下所示,它使用SCAN而不是文档中的KEYS建议。Redis
Something like,
就像是,
var redisScan = require('redisscan');
var redis = require('redis').createClient();
redisScan({
redis: redis,
each_callback: function (type, key, subkey, value, cb) {
console.log(type, key, subkey, value);
cb();
},
done_callback: function (err) {
console.log("-=-=-=-=-=--=-=-=-");
redis.quit();
}
});
回答by Adam Eri
You should never do this. First off, it is not recommended to use KEYS *in production. Second, this does not scale (cluster).
你永远不应该这样做。首先,不建议KEYS *在生产中使用。其次,这不会扩展(集群)。
You can organise your cached entries into SETs and query for the items within the SET, then retrieve the references keys. This also makes invalidation easier.
您可以将缓存的条目组织到 SET 中并查询 SET 中的项目,然后检索引用键。这也使失效更容易。
Have a look at some data storage best practices.
查看一些数据存储最佳实践。
https://redis.io/topics/data-types-introhow to get all keys and values in redis in javascript?
https://redis.io/topics/data-types-intro如何在 javascript 中获取 redis 中的所有键和值?
回答by Iurii Perevertailo
Combination of 2 requests:
2个请求的组合:
import * as ioredis from 'ioredis';
const redis = new ioredis({
port: redisPort,
host: redisServer,
password: '',
db: 0
});
const keys = await redis.collection.keys('*');
const values = await redis.collection.mget(keys);
Order will be the same for both arrays.
两个阵列的顺序相同。
回答by rsp
This will get all keys but with no values:
这将获得所有键但没有值:
const redis = require('redis');
const client = redis.createClient();
client.keys('*', (err, keys) => {
// ...
});
Now you need to get the values for those keys in a usual way. For example:
现在您需要以通常的方式获取这些键的值。例如:
Promise.all(keys.map(key => client.getAsync(key))).then(values => {
// ...
});
or with asyncmodule or in any way you like.
或使用async模块或以您喜欢的任何方式。
回答by Dhiraj
You may find something useful in this link
您可能会在此链接中找到有用的东西
https://github.com/NodeRedis/node_redis/tree/master/examples
https://github.com/NodeRedis/node_redis/tree/master/examples

