Redis migrate 数据迁移工具 - golang

2020-08-12 22:23:59 +08:00
 ysz1121

Redis migrate 数据迁移工具

在工作中可能会遇到单点 Redis 向 Redis 集群迁移数据的问题,但又不能老麻烦运维来做。为了方便研发自己迁移数据,我这里写了一个简单的 Redis 迁移工具,希望对有需要的人有用。

本工具支持:

该工具已经编译成了多平台命令,直接从 Github 下载二进制文件执行就好了。

项目地址: https://github.com/icowan/redis-tool

把代码拉下来之后直接执行命令 make 就可以编译多个平台可执行文件,需要依赖 golang 编译器。

查看使用方法:

$ chmod a+x redis-tool-linux-amd64
$ ./redis-tool-linux-amd64 -h

支持的数据类型

如何使用

下载好命令并授权之后执行 ./redis-tool-linux-amd64 -h 可以查看该工具所支持的所有功能:

$ ./redis-tool-darwin-amd64 migrate -h
数据迁移命令

Usage:
  redis-tool migrate [command]

Examples:

支持命令:
[hash, set, sorted-set, list]


Available Commands:
  all         迁移所有
  hash        哈希列表迁移
  list        列表迁移
  set         redis set 迁移
  sorted-set  有序集合迁移

Flags:
  -h, --help                   help for migrate
      --source-auth string     源密码
      --source-database int    源 database
      --source-hosts string    源 redis 地址, 多个 ip 用','隔开 (default "127.0.0.1:6379")
      --source-prefix string   源 redis 前缀
      --source-redis-cluster   源 redis 是否是集群
      --target-auth string     目标密码
      --target-database int    目标 database
      --target-hosts string    目标 redis 地址, 多个 ip 用','隔开 (default "127.0.0.1:6379")
      --target-prefix string   目标 redis 前缀
      --target-redis-cluster   目标 redis 是否是集群

Use "redis-tool migrate [command] --help" for more information about a command.

参数说明:

迁移单个 key 的数据

下面就举两个例子吧,其他的都差不太多。

Hash 类型

可以通过命令 redis-tool migrate hash -h 查看使用说明

$ redis-tool migrate hash helloworld \
	--source-hosts 127.0.0.1:6379 \
	--target-redis-cluster true \
	--target-hosts 127.0.0.1:6379,127.0.0.1:7379 \
	--target-auth 123456

有序集合

可以通过命令 redis-tool migrate sorted-set -h 查看使用说明

有序集合的数据量可能会比较大,所以这里按 50000 为单位进行了切割。我这里测试过迁移近 17000000 万条的数据,用时 40 多分钟。

$ redis-tool migrate hash helloworld \
	--source-hosts 127.0.0.1:6379 \
	--target-redis-cluster true \
	--target-hosts 127.0.0.1:6379,127.0.0.1:7379 \
	--target-auth 123456

迁移所有 key 的数据支持通配符过滤

可以通过命令 redis-tool migrate all -h 查看使用说明

$ redis-tool migrate all "ipdetect:*" --source-hosts 127.0.0.1:6379 --target-redis-cluster true --target-hosts 127.0.0.1:6379,127.0.0.1:7379 --target-auth 123456

这个命令会编译匹配到的所有类型的 key,再根据 key 的类型进行逐步迁移。

尾巴

使用 golang 写的一个比较简单的工具, 主要用于在 Redis 没有持久化或多套 Redis 向一套 Redis 迁移的情况下使用。

希望对大家有用,谢谢!

2457 次点击
所在节点    Go 编程语言
4 条回复
dic
2020-08-12 23:12:32 +08:00
看到代码里用了 keys 命令,这个命令在 key 比较多的情况下会导致 redis 阻塞,生产环境使用很容易造成服务不可用。
建议参考 https://github.com/alibaba/RedisShake 的同步模式。
hly9469
2020-08-12 23:27:32 +08:00
keys 可以用 scan 来改善
ysz1121
2020-08-13 09:27:35 +08:00
@dic 好的,谢谢~
huixia0010
2020-08-13 12:06:06 +08:00
恩,支持下,总体不错,很赞。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/697808

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX