在分布式系统中,数据同步是一个重要的任务,特别是在将数据从一个 Redis 实例同步到另一个 Redis 实例的情况下。本篇博客将介绍如何使用 Java 编程语言以及 Jedis(Java Redis 客户端)库来实现将本地 Redis 中的所有类型数据同步到阿里云 Redis 实例中。
核心代码
import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisException; import java.util.List; import java.util.Map; import java.util.Set; public class RedisDataSyncAll { public static void main(String[] args) { // 本地 Redis 连接信息 String localHost = "localhost"; int localPort = 6379; JedisPool localJedisPool = new JedisPool(localHost, localPort); // 阿里云 Redis 连接信息 String aliyunHost = "your_aliyun_redis_host"; int aliyunPort = 6379; String aliyunPassword = "your_aliyun_redis_password"; JedisPool aliyunJedisPool = new JedisPool(aliyunHost, aliyunPort); try (Jedis localJedis = localJedisPool.getResource(); Jedis targetJedis = targetJedisPool.getResource()) { targetJedis.auth(aliyunPassword); Set<String> keys = localJedis.keys("*"); if (keys.isEmpty()) { System.out.println("本地Redis数据需要同步."); return; } int syncedCount = 0; for (String key : keys) { try { String type = localJedis.type(key); if ("string".equals(type)) { String value = localJedis.get(key); targetJedis.set(key, value); } else if ("hash".equals(type)) { Map<String, String> hashData = localJedis.hgetAll(key); targetJedis.hmset(key, hashData); } else if ("list".equals(type)) { List<String> listData = localJedis.lrange(key, 0, -1); targetJedis.del(key); // 清空目标 Redis 中的旧数据 targetJedis.lpush(key, listData.toArray(new String[0])); } else if ("set".equals(type)) { Set<String> setData = localJedis.smembers(key); targetJedis.del(key); // 清空目标 Redis 中的旧数据 targetJedis.sadd(key, setData.toArray(new String[0])); } else if ("zset".equals(type)) { Set<redis.clients.jedis.Tuple> zsetData = localJedis.zrangeWithScores(key, 0, -1); targetJedis.del(key); // 清空目标 Redis 中的旧数据 for (redis.clients.jedis.Tuple tuple : zsetData) { targetJedis.zadd(key, tuple.getScore(), tuple.getElement()); } } // 处理过期时间 long ttl = localJedis.ttl(key); if (ttl > 0) { targetJedis.expire(key, (int) ttl); } syncedCount++; } catch (JedisConnectionException e) { // 处理连接异常,例如记录日志、重新尝试等 handleConnectionException(e); } catch (JedisDataException e) { // 处理数据类型异常等 e.printStackTrace(); } catch (JedisException e) { // 处理其他 Redis 异常 e.printStackTrace(); } } if (syncedCount > 0) { System.out.println("Data sync completed. Synced " + syncedCount + " keys."); } else { System.out.println("No data to sync."); } } catch (Exception e) { e.printStackTrace(); } } private static void handleConnectionException(JedisConnectionException e) { // 处理连接异常,例如记录日志、重新尝试等 System.out.println("Connection to Redis failed: " + e.getMessage()); // 可以添加其他处理逻辑,比如重新尝试连接等 } }
标签:targetJedis,java,String,redis,Redis,阿里,key,localJedis From: https://www.cnblogs.com/zyt-bg/p/17641588.html