Redis的分布式和主备配置调研

目前Redis实现集群的方法主要是采用一致性哈稀分片(Shard),将不同的key分配到不同的redis server上,达到横向扩展的目的。
对于一致性哈稀分片的算法,Jedis-2.0.0已经提供了,下面是使用示例代码(以ShardedJedisPool为例):
package com.jd.redis.client;
 
 
 
import java.util.ArrayList;
 
import java.util.List;
 
 
 
import redis.clients.jedis.JedisPoolConfig;
 
import redis.clients.jedis.JedisShardInfo;
 
import redis.clients.jedis.ShardedJedis;
 
import redis.clients.jedis.ShardedJedisPool;
 
import redis.clients.util.Hashing;
 
import redis.clients.util.Sharded;
 
 
 
publicclass RedisShardPoolTest {
 
    static ShardedJedisPoolpool;
 
    static{
 
        JedisPoolConfig config =new JedisPoolConfig();//Jedis池配置
 
        config.setMaxActive(500);//最大活动的对象个数
 
          config.setMaxIdle(1000 * 60);//对象最大空闲时间
 
          config.setMaxWait(1000 * 10);//获取对象时最大等待时间
 
          config.setTestOnBorrow(true);
 
        String hostA = "10.10.224.44";
 
          int portA = 6379;
 
          String hostB = "10.10.224.48";
 
          int portB = 6379;
 
        List<JedisShardInfo> jdsInfoList =new ArrayList<JedisShardInfo>(2);
 
        JedisShardInfo infoA = new JedisShardInfo(hostA, portA);
 
        infoA.setPassword("redis.360buy");
 
        JedisShardInfo infoB = new JedisShardInfo(hostB, portB);
 
        infoB.setPassword("redis.360buy");
 
        jdsInfoList.add(infoA);
 
        jdsInfoList.add(infoB);
 
        

        pool =new ShardedJedisPool(config, jdsInfoList, Hashing.MURMUR_HASH,
 
Sharded.DEFAULT_KEY_TAG_PATTERN);
 
    }
 
    

    /**
 
     * @param args
 
     */
 
    publicstaticvoid main(String[] args) {
 
        for(int i=0; i<100; i++){
 
            String key = generateKey();
 
            //key += "{aaa}";
 
            ShardedJedis jds = null;
 
            try {
 
                jds = pool.getResource();
 
                System.out.println(key+":"+jds.getShard(key).getClient().getHost());
 
                System.out.println(jds.set(key,"1111111111111111111111111111111"));
 
            } catch (Exception e) {
 
                e.printStackTrace();
 
            }
 
            finally{
 
                pool.returnResource(jds);
 
            }
 
        }
 
    }
 
 
 
    privatestaticintindex = 1;
 
    publicstatic String generateKey(){
 
        return String.valueOf(Thread.currentThread().getId())+"_"+(index++);
 
    }
 
}
 1 import java.math.BigDecimal;
 2 import java.text.SimpleDateFormat;
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.Iterator;
 6 import java.util.List;
 7 import java.util.Set;
 8 
 9 import redis.clients.jedis.Jedis;
10 import redis.clients.jedis.JedisPool;
11 import redis.clients.jedis.JedisPoolConfig;
12 
13 public class Test {
14 
15     /**
16      * 测试transfer的应用
17      * @param args
18      */
19     public static void main(String[] args) {
20         testString();
21 
22     }
23     public static void testString() {
24         JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost",6379);
25 
26         Jedis jedis = pool.getResource();
27         try {
28             // 清空数据
29             System.out.println(jedis.flushDB());
30             String date = "20131225154209";
31             String date1 = "20131225154210";
32             String date2 = "20131225154211";
33             String date3 = "20131225154212";
34             
35             HashMap msgMap1=new HashMap();
36             msgMap1.put("ID", "magid1");
37             msgMap1.put("Application", "hotelbe");
38             msgMap1.put("Data", "<OTrequest>reuqeustXML</OTrequest>");
39             msgMap1.put("DataLength", "200");
40             
41             
42             
43             Person person = new Person();
44             person.setAge(BigDecimal.valueOf(23));
45             person.setName("haijun");
46             person.setSex("1");
47             
48             Person person1 = new Person();
49             person1.setAge(BigDecimal.valueOf(23));
50             person1.setName("haijun1");
51             person1.setSex("1");
52             
53             // 添加数据
54             byte[] str = SerializeUtil.serialize(person);
55             byte[] str1 = SerializeUtil.serialize(person1);
56             jedis.zadd("hotelBE".getBytes(), Double.valueOf(date), str);
57             jedis.zadd("hotelBE".getBytes(), Double.valueOf(date1), str1);
58 //            jedis.zadd("hotelCE", Double.valueOf(date2), "zset");
59 //            jedis.zadd("hotelCE", Double.valueOf(date3), "zset!");
60             // 元素个数
61             System.out.println(jedis.zcard("hotelBE"));
62             // 获取指定时间的元素
63             Set<byte[]> set = jedis.zrangeByScore("hotelBE".getBytes(), date.getBytes(), date1.getBytes());
64             int i=0;
65              for( Iterator   it = set.iterator(); it.hasNext(); )
66                 {      
67                  i++;
68                  byte[] persons1 = (byte[]) it.next();
69                  Person person2 = (Person)SerializeUtil.unserialize(persons1);
70                  System.out.println(person2.getName());
71                 }
72              System.out.println("此时间段内的消息个数为:"+i+"个");
73             
74 
75         } finally {
76             // 这里很重要,一旦拿到的jedis实例使用完毕,必须要返还给池中
77             pool.returnResource(jedis);
78         }
79         // 程序关闭时,需要调用关闭方法
80         pool.destroy();
81 
82     }
83     
84     public static String getCurrentDateAndTime() {
85 
86         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
87         return sdf.format(new java.util.Date(System.
88             currentTimeMillis()));
89       }     
90 
91 }
从运行结果中可以看到,不同的key被分配到不同的Redis-Server上去了。
上面的集群模式还存在两个问题:
1.      扩容问题:
因为使用了一致性哈稀进行分片,那么不同的key分布到不同的Redis-Server上,当我们需要扩容时,需要增加机器到分片列表中,这时候会使得同样的key算出来落到跟原来不同的机器上,这样如果要取某一个值,会出现取不到的情况,对于这种情况,Redis的作者提出了一种名为Pre-Sharding的方式:
Pre-Sharding方法是将每一个台物理机上,运行多个不同断口的Redis实例,假如有三个物理机,每个物理机运行三个Redis实际,那么我们的分片列表中实际有9Redis实例,当我们需要扩容时,增加一台物理机,步骤如下:
A.    在新的物理机上运行Redis-Server
B.     Redis-Server从属于(slaveof)分片列表中的某一Redis-Server(假设叫RedisA);
C.     等主从复制(Replication)完成后,将客户端分片列表中RedisAIP和端口改为新物理机上Redis-ServerIP和端口;
D.    停止RedisA
这样相当于将某一Redis-Server转移到了一台新机器上。Prd-Sharding实际上是一种在线扩容的办法,但还是很依赖Redis本身的复制功能的,如果主库快照数据文件过大,这个复制的过程也会很久,同时会给主库带来压力。所以做这个拆分的过程最好选择为业务访问低峰时段进行。
2.      单点故障问题:
还是用到Redis主从复制的功能,两台物理主机上分别都运行有Redis-Server,其中一个Redis-Server是另一个的从库,采用双机热备技术,客户端通过虚拟IP访问主库的物理IP,当主库宕机时,切换到从库的物理IP。只是事后修复主库时,应该将之前的从库改为主库(使用命令slaveofno one),主库变为其从库(使命令slaveofIP PORT),这样才能保证修复期间新增数据的一致性
最终部署的情况会是,分布式的每台server 会有一个对应的备机(从机),这样即使有一个分布式的片机挂掉,对应的备机会接管,不会导致因为片机挂掉导致部分数据不能写进或取出的问题
附件是一份windows下redis服务端程序和客户端需要的jar包,附件下载后后缀改为.rar后解压缩
 可以自己配置分布式和主从测试,
 配置文件着重关注以下配置
 服务端口和 绑定网卡IP
 # Accept connections on the specified port, default is 6379
 port 6178
 
# If you want you can bind a single interface, if the bind option is not
 # specified all the interfaces will listen for connections.
 #
 # bind 127.0.0.1
 

是否为备机(IP:端口)
 ################################# REPLICATION #################################
 
# Master-Slave replication. Use slaveof to make a Redis instance a copy of
 # another Redis server. Note that the configuration is local to the slave
 # so for example it is possible to configure the slave to save the DB with a
 # different interval, or to listen to another port, and so on.
 #
 slaveof 127.0.0.1 6378
 
认证密码
 # If the master is password protected (using the "requirepass" configuration
 # directive below) it is possible to tell the slave to authenticate before
 # starting the replication synchronization process, otherwise the master will
 # refuse the slave request.
 #
 
原文地址:https://www.cnblogs.com/tbyang/p/3491974.html