Redis使用rdb文件恢复数据
只在单台redis恢复,未使用集群。
注意3个配置参数:
appendonly no
dbfilename dump.rdb
dir ./data
appendonly 设置成no,redis启动时会把/var/lib/redis 目录下的dump.rdb 中的数据恢复。dir 和dbfilename 都可以设置。我测试时appendonly 设置成yes 时候不会将dump.rdb文件中的数据恢复。
测试如下:
[root@iZbp143t3oxhfc3ar7jey0Z redis-4.0.12]# redis-cli 127.0.0.1:6379> keys * 1) "user" 127.0.0.1:6379> CONFIG GET dir 1) "dir" 2) "/root/redis-4.0.12/data" 127.0.0.1:6379> set k1 11 OK 127.0.0.1:6379> set k2 11 OK 127.0.0.1:6379> set k3 11 OK 127.0.0.1:6379> set k4 11 OK 127.0.0.1:6379> set k5 11 OK 127.0.0.1:6379> set k6 11 OK 127.0.0.1:6379> set k7 11 OK 127.0.0.1:6379> set k8 11 OK 127.0.0.1:6379> set k9 11 OK 127.0.0.1:6379> set k10 11 OK
连续set10个,就会产生备份
[root@iZbp143t3oxhfc3ar7jey0Z data]# ll total 16 -rw-r--r-- 1 root root 168 Mar 21 14:38 dump.rdb -rw-r--r-- 1 root root 9223 Mar 21 14:38 redis.log [root@iZbp143t3oxhfc3ar7jey0Z data]# mv dump.rdb dump.rdb.bak [root@iZbp143t3oxhfc3ar7jey0Z data]# ll total 16 -rw-r--r-- 1 root root 168 Mar 21 14:38 dump.rdb.bak -rw-r--r-- 1 root root 9223 Mar 21 14:38 redis.log
接着清空整个数据
127.0.0.1:6379> flushall
OK
127.0.0.1:6379> exit
[root@iZbp143t3oxhfc3ar7jey0Z data]# ll total 20 -rw-r--r-- 1 root root 93 Mar 21 14:40 dump.rdb -rw-r--r-- 1 root root 168 Mar 21 14:38 dump.rdb.bak -rw-r--r-- 1 root root 9270 Mar 21 14:40 redis.log
也会产生一个新的rdb,在重新启动redis
[root@iZbp143t3oxhfc3ar7jey0Z redis-4.0.12]# redis-cli shutdown [root@iZbp143t3oxhfc3ar7jey0Z redis-4.0.12]# redis-server redis.conf [root@iZbp143t3oxhfc3ar7jey0Z redis-4.0.12]# lsof -i:6379 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME redis-ser 18150 root 6u IPv6 534722 0t0 TCP *:6379 (LISTEN) redis-ser 18150 root 7u IPv4 534723 0t0 TCP *:6379 (LISTEN) [root@iZbp143t3oxhfc3ar7jey0Z redis-4.0.12]# redis-cli 127.0.0.1:6379> keys * (empty list or set) 127.0.0.1:6379> exit
发现没有数据,是清空后有一个空的备份文件
[root@iZbp143t3oxhfc3ar7jey0Z data]# ll total 20 -rw-r--r-- 1 root root 93 Mar 21 14:41 dump.rdb -rw-r--r-- 1 root root 168 Mar 21 14:38 dump.rdb.bak -rw-r--r-- 1 root root 12281 Mar 21 14:41 redis.log [root@iZbp143t3oxhfc3ar7jey0Z data]# rm -rf dump.rdb [root@iZbp143t3oxhfc3ar7jey0Z data]# mv dump.rdb.bak dump.rdb [root@iZbp143t3oxhfc3ar7jey0Z data]# ll total 16 -rw-r--r-- 1 root root 168 Mar 21 14:38 dump.rdb -rw-r--r-- 1 root root 12281 Mar 21 14:41 redis.log [root@iZbp143t3oxhfc3ar7jey0Z data]#
[root@iZbp143t3oxhfc3ar7jey0Z redis-4.0.12]# redis-cli shutdown [root@iZbp143t3oxhfc3ar7jey0Z redis-4.0.12]# redis-server redis.conf [root@iZbp143t3oxhfc3ar7jey0Z redis-4.0.12]# redis-cli 127.0.0.1:6379> keys * 1) "k10" 2) "k3" 3) "k4" 4) "k2" 5) "k5" 6) "k6" 7) "k1" 8) "k9" 9) "user" 10) "k7" 11) "k8" 127.0.0.1:6379>
把之前产生的rdb文件改名,重新启动,发现就有数据了。