赞
踩
网上基本是都是通过rdb、aof、或者用redis-dump来实现数据迁移,步骤都挺复杂的,完全可以通过go直接编译一个可执行程序来实现可快实现快速迁移。
由于集群模式数据是分散的,所以复制的过程还需要考虑MOVED的情况
1、安装依赖库
go get github.com/go-redis/redis
2.代码内容
下面是参考代码,可以修改ip、端口与密码参数并根据自己需要进行调整
- package main
-
- import (
- "fmt"
- "log"
- "strings"
-
- "github.com/go-redis/redis"
- )
-
- func main() {
- // 连接源 Redis 集群
- sourceClient := redis.NewClusterClient(&redis.ClusterOptions{
- Addrs: []string{"172.16.0.12:7001", "172.16.0.12:7002", "172.16.0.12:7003", "172.16.0.15:7001", "172.16.0.15:7002", "172.16.0.15:7003"},
- Password: "auth-password",
- })
-
- // 连接目标 Redis 服务器
- destClient := redis.NewClient(&redis.Options{
- Addr: "目标RedisIP:目标Redis端口",
- Password: "auth-password",
- })
-
- // 获取源 Redis 集群中的所有键
- keys, err := sourceClient.Keys("*").Result()
- if err != nil {
- log.Fatal(err)
- }
-
- // 遍历所有键并导入到目标 Redis 服务器
- for _, key := range keys {
- val, err := sourceClient.Get(key).Result()
- if err != nil {
- log.Printf("Failed to get key %s: %v", key, err)
- continue
- }
-
- err = destClient.Set(key, val, 0).Err()
- if err != nil {
- if strings.Contains(err.Error(), "MOVED") {
- parts := strings.Fields(err.Error())
- addr := parts[2]
- sourceClient := redis.NewClusterClient(&redis.ClusterOptions{
- Addrs: []string{addr},
- Password: "auth-password",
- })
- val, err := sourceClient.Get(key).Result()
- if err != nil {
- log.Printf("Failed to get key %s: %v", key, err)
- continue
- }
- err = destClient.Set(key, val, 0).Err()
- if err != nil {
- log.Printf("Failed to set key %s: %v", key, err)
- continue
- }
- fmt.Printf("Key %s moved from %s, successfully imported.\n", key, addr)
- } else {
- log.Printf("Failed to set key %s: %v", key, err)
- continue
- }
- }
- fmt.Printf("Key %s imported successfully.\n", key)
- }
-
- fmt.Println("Data migration completed.")
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。