如何在 Redis (NodeJS) 中查找数据库数量 [英] How to find number of databases in Redis (NodeJS)

查看:34
本文介绍了如何在 Redis (NodeJS) 中查找数据库数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在编写一个从 redis 读取的节点应用程序,我想做一个返回数据库数量的查询,有没有人知道怎么做.

所以现在基本上我拥有的是一种获取数据库中所有键的方法,但我想要更高的级别,我想遍历所有数据库然后获取所有键.这是获取当前DB的所有key的代码.

const client = redis.createClient({host: "127.0.0.1", port: 6379});客户端.multi().keys('*', function (err, 回复) {console.log("MULTI got " + replies.length + " replies");让 dbs = [回复];让 dbData = {};回复.forEach(函数(回复,索引){client.get(reply, function (err, data) {console.log(reply + " " +data);});});}).exec(function (err, 回复) { });

解决方案

解决方案 1

正如@carebdayrvis 提到的,您可以使用INFO 命令获取数据库信息,并解析信息以获取数据库数量.

这个解决方案有两个问题:

  1. 它只返回非空数据库的信息.它不会显示数据库的总数.
  2. 如果信息文本的格式发生变化,您必须重新编写解析代码.

<块引用>

解决方案 2

调用CONFIG GET DATABASES 获取数据库总数.此结果包括空数据库和非空数据库.您可以使用 SELECT db-indexDBSIZE 命令来确定哪些数据库不是空的.

此解决方案的优点是更具可编程性.

<块引用>

其他东西

顺便说一下,KEYS 不应该在生产环境中使用,它可能会长时间阻塞Redis.您应该考虑改用 SCAN 命令.

So I am writing a node app that reads from redis, I would like to do a query of some sort that returns the number of databases does anyone know how to do that.

So right now basically what I have is a way to get all keys in a database but I want the level higher, I want to iterate over all databases and then get all keys. This is the code for getting all the keys for the current DB.

const client = redis.createClient({host: "127.0.0.1", port: 6379});
client.multi()
    .keys('*', function (err, replies) {
        console.log("MULTI got " + replies.length + " replies");
        let dbs = [replies];
        let dbData = {};
        replies.forEach(function (reply, index) {
            client.get(reply, function (err, data) {
                console.log(reply + " " +data);
            });
        });

    })
    .exec(function (err, replies) { });

解决方案

Solution 1

As @carebdayrvis mentioned, you can use INFO command to get the database info, and parse the info to get the number of databases.

There're two problems with this solution:

  1. It only returns the info of databases that are NOT empty. It doesn't show you the total number of databases.
  2. If the format of the info text changes, you have to rewrite the parsing code.

Solution 2

Call CONFIG GET DATABASES to get the total number of databases. This result includes both empty and non-empty databases. You can use SELECT db-index and DBSIZE commands to figure out which databases are NOT empty.

The advantage of this solution is that it's more programmable.

Other Stuff

By the way, KEYS should NOT be used in production environment, it might block Redis for a long time. You should consider using SCAN command instead.

这篇关于如何在 Redis (NodeJS) 中查找数据库数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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