1. Introduction
1.简介
In this short tutorial, we’ll take a look at different ways to list all the databases available in Redis.
在这个简短的教程中,我们将看看列出Redis中所有可用数据库的不同方法。
2. Listing All Databases
2.列出所有数据库
In the first place, the number of databases in Redis is fixed. Therefore, we can extract this information from the configuration file with a simple grep command:
首先,Redis中的数据库数量是固定的。因此,我们可以通过一个简单的grep命令从配置文件中提取这一信息。
$ cat redis.conf | grep databases
databases 16
But what if we don’t have access to the configuration file? In this case, we can get the information we need by reading the configuration at runtime via the redis-cli:
但如果我们不能访问配置文件呢?在这种情况下,我们可以通过redis-cli在运行时读取配置来获得我们需要的信息。
127.0.0.1:6379> CONFIG GET databases
1) "databases"
2) "16"
Lastly, even though it’s more suitable for low-level applications, we can use the Redis Serialization Protocol (RESP) through a telnet connection:
最后,尽管它更适合于低级别的应用,我们可以通过telnet连接使用Redis序列化协议(RESP)。
$ telnet 127.0.0.1 6379
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
*3
$6
CONFIG
$3
GET
$9
databases
*2
$9
databases
$2
16
3. Listing All Databases With Entries
3.列出所有有条目的数据库
Sometimes we’ll want to get more information about the databases that contain keys. In order to do that, we can take advantage of the Redis INFO command, used to get information and statistics about the server. Here, we specifically want to focus our attention in the keyspace section, which contains database-related data:
有时我们会想获得更多关于包含键的数据库的信息。为了做到这一点,我们可以利用Redis的INFO命令,用来获取关于服务器的信息和统计数据。在这里,我们特别想把注意力集中在keyspace部分,它包含与数据库相关的数据。
127.0.0.1:6379> INFO keyspace
# Keyspace
db0:keys=2,expires=0,avg_ttl=0
db1:keys=4,expires=0,avg_ttl=0
db2:keys=9,expires=0,avg_ttl=0
The output lists the databases containing at least one key, along with a few statistics:
输出结果列出了至少包含一个键的数据库,以及一些统计数据。
- number of keys contained
- number of keys with expiration
- keys’ average time-to-live
4. Conclusion
4.结论
To sum up, this article went through different ways of listing databases in Redis. As we’ve seen, there are different solutions, and which one we choose really depends on what we’re trying to achieve.
总而言之,本文介绍了在Redis中列出数据库的不同方法。正如我们所看到的,有不同的解决方案,而我们选择哪一种,真的取决于我们想要实现的目标。
A grep is generally the best option if we have access to the config file. Otherwise, we can use the redis-cli. RESP is not usually a good choice unless we’re building an application that needs a low-level protocol. Finally, the INFO command is useful if we want to retrieve only databases that contain keys.
如果我们能够访问配置文件,grep通常是最好的选择。否则,我们可以使用redis-cli。RESP通常不是一个好的选择,除非我们正在构建一个需要低级协议的应用程序。最后,如果我们想只检索包含键的数据库,INFO命令很有用。