Redis实现分布式存储的方法主要是采用一致性哈稀分片(Shard),将不同的key分配到不同的redis server上,达到横向扩展的目的。
package redis; 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; public class RedisShardPoolTest { static ShardedJedisPool pool; static {
JedisPoolConfig config = new JedisPoolConfig();// Jedis池配置
config.setMaxTotal(500);// 最大活动的对象个数
config.setMaxIdle(1000 * 60);// 对象最大空闲时间
config.setMaxWaitMillis(1000 * 10);// 获取对象时最大等待时间
config.setTestOnBorrow(true);
String hostA = "192.168.77.135";
int portA = 6378;
String hostB = "192.168.77.135";
int portB = 6380;
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
*/ public static void main(String[] args) {
ShardedJedis jds = null;
// key += "{aaa}";
try {
jds = pool.getResource();
for (int i = 0; i < 100; i++) {
String key = generateKey();
System.out.println(key + ":" + jds.getShard(key).getClient().getHost() + ":" + jds.getShard(key).getClient().getPort());
System.out.println(jds.set(key, "1111111111111111111111111111111"));
System.out.println(jds.get(key));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.returnResource(jds);
}
} private static int index = 1; public static String generateKey() {
return String.valueOf(Thread.currentThread().getId()) + "_" + (index++);
}
}