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

 

Redis主从模式的配置:

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

cp redis.conf redis-slave.conf

redis主从负载 redis主从模式配置_配置文件

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

redis主从负载 redis主从模式配置_redis主从负载_02

redis主从负载 redis主从模式配置_redis主从负载_03

 

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

修改redis-slave.conf配置文件

redis主从负载 redis主从模式配置_redis主从负载_04

 

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

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

redis主从负载 redis主从模式配置_配置文件_05

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

redis主从负载 redis主从模式配置_redis_06

redis主从负载 redis主从模式配置_redis主从负载_07

 

测试:

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

 

redis主从负载 redis主从模式配置_配置文件_08

redis主从负载 redis主从模式配置_服务器_09

 

 主从模式代码:

redis主从负载 redis主从模式配置_配置文件_10

redis主从负载 redis主从模式配置_redis_11

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

代码执行前:

redis主从负载 redis主从模式配置_redis主从负载_12

执行后:

redis主从负载 redis主从模式配置_Redis主从模式_13

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

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

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