如何在javascript中获取redis中的所有键和值? [英] how to get all keys and values in redis in javascript?

查看:29
本文介绍了如何在javascript中获取redis中的所有键和值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 javascript 创建一个节点 API.我使用 redis 作为我的键值存储.我在我的应用程序中创建了一个 redis 客户端,并且能够获取特定键的值.

我想检索所有键及其值.到目前为止,我已经这样做了:

app.get('/jobs', function (req, res) {var 工作 = [];client.keys('*', function (err, keys) {if (err) 返回 console.log(err);如果(键){for(var i=0;i

但我总是得到空白数组作为响应.

有没有办法在javascript中做到这一点?

谢谢

解决方案

首先,你的问题的问题是,在 for 循环内,client.get 使用 异步 回调调用,其中 同步 for 循环不会等待异步回调,因此下一行 res.json({data:jobs}); 在异步回调之前的 for 循环之后立即被调用.在行 res.json({data:jobs}); 被调用时,数组 jobs 仍然是空的 []并返回响应.

为了缓解这种情况,您应该使用任何承诺模块,例如 asyncbluebirdES6 Promise 等.

使用async模块修改代码,

app.get('/jobs', function (req, res) {var 工作 = [];client.keys('*', function (err, keys) {if (err) 返回 console.log(err);如果(键){async.map(keys, function(key, cb) {client.get(key, function (error, value) {如果(错误)返回 cb(错误);var 工作 = {};工作['jobId']=key;工作['数据']=值;cb(空,工作);});}, 函数(错误,结果){if (error) return console.log(error);控制台日志(结果);res.json({数据:结果});});}});});

<块引用>

但是从 Redis documentation 可以看出,使用键用于调试和特殊操作,例如更改您的键空间布局,不建议用于生产环境.

因此,我建议使用另一个名为 redisscan 的模块,如下所示,它使用 SCAN 而不是 KEYSRedis 文档中所建议的.

类似的东西,

var redisScan = require('redisscan');var redis = require('redis').createClient();重新扫描({Redis: Redis,each_callback:函数(类型、键、子键、值、cb){控制台日志(类型,键,子键,值);cb();},done_callback:函数(错误){console.log("-=-=-=-=-=--=-=-=-");redis.quit();}});

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.

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?

Thanks

解决方案

First of all, the issue in your question is that, inside the for loop, client.get is invoked with an asynchronous callback where the synchronous for loop will not wait for the asynchronous callback and hence the next line res.json({data:jobs}); is getting called immediately after the for loop before the asynchronous callbacks. At the time of the line res.json({data:jobs}); is getting invoked, the array jobs is still empty [] and getting returned with the response.

To mitigate this, you should use any promise modules like async, bluebird, ES6 Promise etc.

Modified code using async module,

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 Redis documentation, 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.

Hence, I would suggest using another module called redisscan as below which uses SCAN instead of KEYS as suggested in the Redis documentation.

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();
        }
    });

这篇关于如何在javascript中获取redis中的所有键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆