Redis 默认提供了 16 个数据库。每个数据库都有一个 id , 从 0 开始,[0,15]。 不同的数据库中数据隔离保存。我们可以通过修改 redis 的配置文件进行修改数据库的数量。
1 | database 32 |
- 使用
select <ID>可以切换数据库.
示例如下:
1 | 127.0.0.1:6379> select 1 |
可以通过命令之前的部分区分我们所在的数据库.
127.0.0.1:6379[2]> select 2 执行这个命令的时候,我们是在数据库 1 中的。
- 使用
flushdb只能删除 该数据库 (一个库) 中的数据。 - 使用
flushall可以删除 所有库 中的数据。
# redis 使用分库的意义
- 避免不同应用相同
key的影响。 - 更便于管理。
一个实例上运行多个库,只运维这一个实例就可以了。 - 也有不少文章说,redis 的作者曾说过,“多数据库的设计可能是最糟糕的决定.”. Redis 是单线程的,即使是多数据库也不会带来性能提升。但是这个并没有和前面的两个好处冲突。下面是作者的原话:
I understand how this can be useful, but unfortunately I consider Redis multiple database errors my worst decision in Redis design at all… without any kind of real gain, it makes the internals a lot more complex. The reality is that databases don’t scale well for a number of reason, like active expire of keys and VM. If the DB selection can be performed with a string I can see this feature being used as a scalable O(1) dictionary layer, that instead it is not.
With DB numbers, with a default of a few DBs, we are communication better what this feature is and how can be used I think. I hope that at some point we can drop the multiple DBs support at all, but I think it is probably too late as there is a number of people relying on this feature for their work.
# Redis 的分库是怎么实现?
Redis 服务器间所有的数据库都保存在 服务器状态 redis.h/redisServer 结构的 db 数组中。 db 数组中的每个元素都是一个 redis.h/redisDb 结构。每个 redisDb 结构代表一个数据库.
1 | struct redisServer { |
每个 Redis 客户端都有自己的目标数据库,每个客户端执行数据库写命令或者数据库读命令的时候,目标数据库都会成为这些命令的操作对象.
每个客户端用 RedisClient 来描述。 RedisClient 结构的 db 属性记录了客户端当前的目标数据库,这个属性是一个指向 redisDb 的指针.
1 | typedef struct redisClient { |
# 举个例子:
假设我们客户端连接的是数据库 1 , 那么客户端与服务器端之间的关系是这样的:

如果我们运行 select 2 , 其实,就是改变的 db 的指针。让它指向了 db(2) , 这就是 select 命令的运行原理。如下图。

以上就是 关于 Redis 多数据库的内容了。
# 最后
期望与你一起遇见更好的自己
