Redis主从配置与数据备份还原

时间:2022-09-14 09:32:02

一、主从配置:

1、下载:

wget http://download.redis.io/releases/redis-4.0.9.tar.gz

tar xzf redis-4.0.9.tar.gz

cd redis-4.0.9.tar.gz

make

cd src/

make install

mkdir -p /usr/local/redis/etc

cd ../

cp -a redis.conf /usr/local/redis/etc

2、创建用户:

groupadd redis
useradd -g redis redis -s /sbin/nologin

3、修改配置文件:

主修改的配置:

sed -i "s#bind 127.0.0.1#bind 0.0.0.0#g" redis.conf

sed -i "s#daemonize no#daemonize yes#g" redis.conf

sed -i "s#protected-mode yes#protected-mode no#g" redis.conf
sed -i "s@# requirepass foobared@requirepass 123456@g" redis.conf
sed -i "s#port 6379#port 16379#g" redis.conf
sed -i "s#pidfile /var/run/redis_6379.pid#pidfile /usr/local/redis_16379.pid#g" redis.conf

从修改的配置:

sed -i "s#bind 127.0.0.1#bind 0.0.0.0#g" redis.conf

sed -i "s#daemonize no#daemonize yes#g" redis.conf

sed -i "s#protected-mode yes#protected-mode no#g" redis.conf
sed -i "s@# requirepass foobared@requirepass 123456@g" redis.conf
sed -i "s#port 6379#port 16380#g" redis.conf
sed -i "s#pidfile /var/run/redis_6379.pid#pidfile /usr/local/redis_16380.pid#g" redis.conf

sed -i "s@# slaveof <masterip> <masterport>@slaveof 192.168.1.125 16379@g" redis.conf
sed -i "s@# masterauth <master-password>@masterauth 123456@g" redis.conf

4、修改目录权限:

chown -R redis:redis /usr/local/redis

5、以redis用户启动redis进程:

sudo -u redis /usr/local/redis/bin/redis-server /usr/local/redis/etc/redis.conf

6、验证:

连接master:

./redis-cli -p 16379 -a 123456

127.0.0.1:16379> info

Redis主从配置与数据备份还原

127.0.0.1:16379> set name abc

OK

127.0.0.1:16379> get name

"abc"

连接slave验证:

./redis-cli -p 16380 -a 123456

127.0.0.1:16380> get name

"abc"

 

 

 

 

二:数据的备份与还原

1、进入redis客户端:

127.0.0.1:16379> set game wow

OK

127.0.0.1:16379> get game
"wow"

启动备份:

127.0.0.1:16379> save

127.0.0.1:16379> bgsave      #启动一个子进程,在后台备份

2、获取备份的目录所在:

127.0.0.1:16379> CONFIG GET dir

1) "dir"
2) "/usr/local/redis"

3、停止redis服务,将备份的文件放在上面查到的目录中,然后启动Redis:

sudo -u redis /usr/local/redis/bin/redis-server /usr/local/redis/etc/redis.conf

4、验证:

进入客户端:

./redis-cli -p 16379 -a 123456

127.0.0.1:16379> get game
"wow"

 

 

 

报错:

127.0.0.1:16379> save
(error) ERR

可能是因为你目录没有设置对,注意权限问题。重新设置目录即可