实现将redis中的所有数据备份到数据库表中
bash
/**
* 将redis中的数据同步到mysql中
*/
@Override
public void saveMysqlForRedis(){
Jedis jedis = new Jedis("127.0.0.1", 6379);
//System.out.println(jedis.ping());
Set keys = jedis.keys("*");//列出所有的key
Iterator t1 = keys.iterator();
while (t1.hasNext()){
Object obj1 = t1.next();
saveRedisObject(jedis,obj1+"","127.0.0.1","6379");
}
}
//存储单个对象
public void saveRedisObject(final Jedis jedis,final String rediskey,final String macIp,final String port ){
String redisType = jedis.type(rediskey);//返回值的类型
RedisTable redisTable = new RedisTable();
redisTable.setRediskey(rediskey);
redisTable.setRedistype(redisType+"/");
//set集合
if("set".equalsIgnoreCase(redisType)){
Set<String> setStrings = jedis.smembers(rediskey);
if(null!=setStrings && !setStrings.isEmpty()){
Iterator setIterator = setStrings.iterator();
while (setIterator.hasNext()){
Object obj1 = setIterator.next();
redisTable.setRedisvalue(obj1+"");
redisTableService.insert(redisTable);//save
}
}
}
//hash
else if ("hash".equalsIgnoreCase(redisType)) {
Set<String> hashSet = jedis.hkeys(rediskey);
if(null != hashSet && !hashSet.isEmpty()){
Iterator setIterator = hashSet.iterator();
while (setIterator.hasNext()){
String objectName = setIterator.next()+"";
redisTable.setRedisvalue(jedis.hget(rediskey,objectName));
redisTableService.insert(redisTable);//save
}
}
}else if("string".equalsIgnoreCase(redisType)){
redisTable.setRedisvalue((jedis.get(rediskey)));
redisTableService.insert(redisTable);//save
}
}
...同样的,还有redis的其他数据类型,如下图:
注意:
1.需要考虑redis和mysql数据的一致性;
2.考虑redis数据导入的数据的重复性问题。