Redis- Replication

Replication

Replicating the data from master to slave and use the slave DB instances for reading purpose if you have very heavy read queries on master.





How to Setup Replication in Redis

Generally, We will have two different hosts where we will run this Redis server and we will replicate the data from Redis-Server1 to Redis-Server2. But here we are running redis on same machine with two different port no. and trying to replicate the data between them.

Redis Server 1: Port 6379 and Datafile: db1.rds
Redis Server 2: Port 6380 and Datafile: db2.rds


Step 1: Start the Redis Server1 with Port 6379. So we will run the command
 redis-server --port 6379 --dbfilename db1.rds


Step 2: Start the Redis Server2 with Port 6380 with following command.
 redis-server --port 6380 --dbfilename db2.rds




Step 3: Now, connect to Redis client using port no. and try to check the health using ping command.
           Redis-cli -p 6379 and Redis-cli -p 6380


Using the Info command, you can check the role on both the instance it is showing as a master and connected slaves: 0 
       info replication

Redis Server(6379): 9760fc1fa02a89249944f19b3551a3972d89e7f7
Redis Server(6380): ddf0658e099a76cb77a5c03828fc289fd7eefd8c

So, we have validated that both the server are independent and there is no replication in between.

Step 4: Let setup, the replication between these two instance. where we will try to replicate the data from Redis Server1(6379) to Redis Server2(6380).

To Setup the replication we have run following command. 

      Replicaof <hostname> <port>

We have to run this command to server which we want to make as a replica so here we gone run it on Redis-Server2(6380).

In our case both the server are running on localhost so we will pass hostname as localhost.





In the above screenshot you can noticed the its trying connect localhost:6379 and master-replica sync started.

Now, to validate the replication between master and slave, rerun the info command and check the role, master port.

Info Replication on 6379 as master


Info Replication on 6380 as slave


So, Your Replication completed successfully between master and slave. 

Try to some key on master server and see its replicating on the salve server.

Set K1 V1

Write to create Keys on Replica, you will notice that ERROR Readonly you can't write.


To disable the replication between master and replication use below command.

    Replicaof no one

Once you disable the replication, you slave become master again.