Redis
默認提供了16
個數據庫. 每個數據庫都有一個id
, 從 0
開始, [0,15]。 不同的數據庫中數據隔離保存。我們可以通過修改redis的配置文件進行修改數據庫的數量。
database 32
- 使用
select <ID>
可以切換數據庫.
示例如下:
127.0.0.1:6379> select 1
OK
# 演示數據隔離
127.0.0.1:6379[1]> set test 1
OK
127.0.0.1:6379[1]> select 2
Ok
127.0.0.1:6379[2]> get test
(nil)
可以通過命令之前的部分區分我們所在的數據庫.
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
結構代表一個數據庫.
struct redisServer {
// 保存所有數據庫
redisDb *db;
// 數據庫的數量(redis.conf文件中 database配置的)
int dbnum;
}
每個Redis
客戶端都有自己的目標數據庫,每個客戶端執行數據庫寫命令或者數據庫讀命令的時候,目標數據庫都會成爲這些命令的操作對象.
每個客戶端用 RedisClient
來描述。 RedisClient
結構的db
屬性記錄了客戶端當前的目標數據庫,這個屬性是一個指向 redisDb
的指針.
typedef struct redisClient {
// 記錄客戶端端正在使用的數據庫id
redisDb *db;
} redisClient;
舉個例子:
假設我們客戶端連接的是數據庫1
,那麼客戶端與服務器端之間的關係是這樣的:
如果我們運行 select 2
, 其實,就是改變的db的指針。讓它指向了 db(2)
,這就是 select
命令的運行原理. 如下圖。
以上就是 關於 Redis
多數據庫的內容了。
最後
希望和你成爲朋友!我們一起學習~
最新文章盡在公衆號【方家小白】,期待和你相逢在【方家小白】