将两个 Redis 实例合并为一个带有两个 dbs 的实例 [英] Combine two Redis instances into a single instance with two dbs
问题描述
我有两个 Redis 实例(或两个各自的 dump.rdb 文件),我想将它们组合成一个带有两个 dbs 的单个实例,每个对应的初始实例一个.
I have two Redis instances (or two respective dump.rdb files) and I would like to combine them into a single instance with two dbs, one for each respective initial instance.
我可以使用 MIGRATE 做到这一点,但它仅在 Redis 2.6.0 中可用,我当前的 Redis 服务器不支持.
I could do this using MIGRATE, but it is only available in Redis 2.6.0, which is not supported by my current Redis server.
推荐答案
EDIT
对于较新版本的 redis,此答案不再准确.出于历史原因留下答案.
EDIT
This answer is no longer accurate for newer versions of redis. Leaving the answer for historical reasons.
如果您愿意稍微处理一下二进制文件,您可以轻松地将两个 dump.rdb 文件合二为一.
If you are willing to play around a bit with binary files, you can easily combine the two dump.rdb files into one.
假设:
- 每个转储只有一个数据库 - 默认数据库
- 您使用的是 Redis 2.4.x,因此转储版本为 2 或 3
如果在十六进制编辑器中打开文件,这是RDB文件的格式 -
If you open the file in a hex editor, this is the format of the RDB file -
REDIS000x FE 00 <实际数据>FF
这里 -
000x
是 rdb 版本号.在您的情况下,它很可能是 0002 或 0003FE
为数据库选择器,00
为数据库编号
是当前数据库中的键值对.您可以将其视为当前用途的二进制 blob.FF
是文件的最后一个字节,表示rdb文件的结尾
000x
is the rdb version number. It will most likely be 0002 or 0003 in your caseFE
is the database selector, and00
is the database number<actual data>
is the key-value pairs in the current database. You can treat this as a binary blob for your current purpose.FF
is the last byte in the file and indicates the end of the rdb file
因此要合并两个 rdb 文件,请执行以下操作 -
So to merge the two rdb files, do the following -
- 创建一个新的目标文件
- 复制第一个文件中除最后一个
FF
之外的所有内容 - 复制两个字节
FE 01
表示第二个数据库的开始 - 注意:如果您确定两个数据库没有重复的键,并且您想将它们组合成一个数据库,只需跳过上面提到的两个字节
FE 01
. - 从第二个文件中,跳过前 11 个字节 - 即跳过
REDIS000x FE 00
- 复制第二个文件的其余部分,包括最后一个字节
FF
- Create a new destination file
- Copy everything from the first file except the last
FF
- Copy two bytes
FE 01
to indicate start of second database - NOTE : If you are sure the two databases don't have duplicate keys, and you want to combine them into a single database, simply skip the two bytes
FE 01
mentioned above. - From the second file, skip the first 11 bytes - i.e. skip
REDIS000x FE 00
- Copy over the rest of the second file, including the last byte
FF
您现在可以将这个新的 dump.rdb 复制到 redis 中的相应目录并重新启动.
You can now copy this new dump.rdb to the appropriate directory in redis and restart.
如果你有兴趣,这里是redis 转储文件格式的完整文档,但对于这个简单的用例,您无需了解所有内容.
If you are interested, here is complete documentation of redis dump file format, but you don't need to understand all of it for this simple use case.
这篇关于将两个 Redis 实例合并为一个带有两个 dbs 的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!