Redis主从模式

为了提高redis的性能,可以创建基于主从模式的redis,在主服务器上负责写操作,从服务器上进行读取操作。

Redis主从模式的配置:

1.复制redis.conf文件到/usr/local/bin目录下,命名为redis-slave.conf,修改端口号为6479,基于该文件做从服务器

cp redis.conf redis-slave.conf

2.修改redis-slave.conf配置文件

这里我们将端口为6479的redis服务器作为端口为6379服务器的从服务器

修改redis-slave.conf配置文件

修改完后,启动主从服务器:

[root@localhost bin]# redis-server redis.conf
[root@localhost bin]# redis-server redis-slave.conf

连接reids主从服务器,查看主从信息

测试:

主机上设置a的值为10,从机上获取a

 

 主从模式代码:

package com.study.util;

import redis.clients.jedis.Jedis;

public class RedisMasterSlave {

    public static void main(String[] args) throws InterruptedException {
        Jedis master = new Jedis("192.168.150.129",6379);//主机  
        master.auth("1234");
        Jedis slave = new Jedis("192.168.150.129",6579);//从机  
        slave.auth("1234");
        //设置6579服务器的主机为6379
        slave.slaveof("192.168.150.129",6379);  
      
        master.select(1);
        master.setex("a",100,"100");//主机去写  
          
        //延迟一秒,防止内存中读写太快,读在写之前先完成而出现null的情况  
        Thread.sleep(1000);  
        
        slave.select(1);
        String result = slave.get("a");//从机去读  
        System.out.println(result);  
        
        master.close();
        slave.close();
    }
}
View Code

代码执行前:

执行后:

注:端口为6579的redis服务器为新配的服务器,在代码执行前配置文件并没有配置他的主服务器,此时它作为一个单独的服务器运行,

在执行代码slave.slaveof("192.168.150.129",6379);  后,它被设置为6379的从服务器,此时端口为6379的服务器就有6479和6579两台从服务器。

代码git地址:https://gitee.com/sjcq/redis.git

猜你喜欢

转载自www.cnblogs.com/sjcq/p/8973512.html