目前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++);
}
}
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class Test {
/\*\*
\* 测试transfer的应用
\* @param args
\*/
public static void main(String\[\] args) {
testString();
}
public static void testString() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost",6379);
Jedis jedis = pool.getResource();
try {
// 清空数据
System.out.println(jedis.flushDB());
String date = "20131225154209";
String date1 = "20131225154210";
String date2 = "20131225154211";
String date3 = "20131225154212";
HashMap msgMap1=new HashMap();
msgMap1.put("ID", "magid1");
msgMap1.put("Application", "hotelbe");
msgMap1.put("Data", "<OTrequest>reuqeustXML</OTrequest>");
msgMap1.put("DataLength", "200");
Person person = new Person();
person.setAge(BigDecimal.valueOf(23));
person.setName("haijun");
person.setSex("1");
Person person1 = new Person();
person1.setAge(BigDecimal.valueOf(23));
person1.setName("haijun1");
person1.setSex("1");
// 添加数据
byte\[\] str = SerializeUtil.serialize(person);
byte\[\] str1 = SerializeUtil.serialize(person1);
jedis.zadd("hotelBE".getBytes(), Double.valueOf(date), str);
jedis.zadd("hotelBE".getBytes(), Double.valueOf(date1), str1);
// jedis.zadd("hotelCE", Double.valueOf(date2), "zset");
// jedis.zadd("hotelCE", Double.valueOf(date3), "zset!");
// 元素个数
System.out.println(jedis.zcard("hotelBE"));
// 获取指定时间的元素
Set
int i=0;
for( Iterator it = set.iterator(); it.hasNext(); )
{
i++;
byte[] persons1 = (byte[]) it.next();
Person person2 = (Person)SerializeUtil.unserialize(persons1);
System.out.println(person2.getName());
}
System.out.println("此时间段内的消息个数为:"+i+"个");
} finally {
// 这里很重要,一旦拿到的jedis实例使用完毕,必须要返还给池中
pool.returnResource(jedis);
}
// 程序关闭时,需要调用关闭方法
pool.destroy();
}
public static String getCurrentDateAndTime() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
return sdf.format(new java.util.Date(System.
currentTimeMillis()));
}
}
从运行结果中可以看到,不同的key被分配到不同的Redis-Server上去了。
上面的集群模式还存在两个问题:
1. 扩容问题:
因为使用了一致性哈稀进行分片,那么不同的key分布到不同的Redis-Server上,当我们需要扩容时,需要增加机器到分片列表中,这时候会使得同样的key算出来落到跟原来不同的机器上,这样如果要取某一个值,会出现取不到的情况,对于这种情况,Redis的作者提出了一种名为Pre-Sharding的方式:
Pre-Sharding方法是将每一个台物理机上,运行多个不同断口的Redis实例,假如有三个物理机,每个物理机运行三个Redis实际,那么我们的分片列表中实际有9个Redis实例,当我们需要扩容时,增加一台物理机,步骤如下:
A. 在新的物理机上运行Redis-Server;
B. 该Redis-Server从属于(slaveof)分片列表中的某一Redis-Server(假设叫RedisA);
C. 等主从复制(Replication)完成后,将客户端分片列表中RedisA的IP和端口改为新物理机上Redis-Server的IP和端口;
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
# specified all the interfaces will listen for connections.
#
# bind 127.0.0.1
是否为备机(IP:端口)
################################# REPLICATION #################################
# 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.
#
手机扫一扫
移动阅读更方便
你可能感兴趣的文章