@BeforeClass
public static void createPool() {
JedisPoolConfig poolConfig = JedisUtils.getMyDefaultJedisPoolConfig();
// List<JedisShardInfo> shards = Arrays.asList(new JedisShardInfo("192.168.3.98", 6379)
// , new JedisShardInfo("192.168.3.98", 6380));
List<JedisShardInfo> shards = Lists.newArrayList();
JedisShardInfo info1 = new JedisShardInfo("192.168.3.98", 6379);
JedisShardInfo info2 = new JedisShardInfo("192.168.3.98", 6380);
// 添加的顺序有意义
shards.add(info1);
shards.add(info2);
pool = new ShardedJedisPool(poolConfig, shards);
}
@Before
public void getResource() {
jedis = pool.getResource();
}
@After
public void destroyJedis() {
pool.returnResource(jedis);
}
@AfterClass
public static void destroyPool() {
pool.destroy();
}
/**
* 不同的key分配根据List<JedisShardInfo>中的顺序,分配不同的Redis连接
*/
@Test
public void testSet() {
for (int i = 0; i < 20; i++) {
try {
logger.info(i + " - " + jedis.getShard("" + i).getClient().getHost()
+ " : " + jedis.getShard(i + "").getClient().getPort());
logger.info(jedis.set("" + i, "true"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 修改List<JedisShardInfo>中的顺序,无法得到结果,确定该顺序是有意义的
*/
@Test
public void testGet() {
for (int i = 0; i < 20; i++) {
try {
logger.info(i + " - " + jedis.getShard(i + "").getClient().getHost()
+ ":" + jedis.getShard(i + "").getClient().getPort() + " ? " + jedis.get("" + i));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
二.Redis主从复制
redis的主重复制有两种方式,第一种是写在.conf配置文件中,第二种是通过命令slaveof ip port 或 slaveof no one
slaveof no one 之后,当前Redis节点提升为Master但之前数据不会丢失,所以通过程序动态的设置主从复制可以解决Redis单点故障的问题