考慮到互聯網使用環境極其複雜,需要高效穩定的redis環境,redis3.0增加了cluster功能,可以給redis集羣部署,這樣的好處是性能穩定,但是缺點是非常重,運營不方便,並且至少需要部署6個節點,而且有坑。
下面轉載了一個同學的文章來搭建集羣部署環境,http://www.cnblogs.com/Xrinehart/p/3502213.html。
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
public class redisClusterConcurrent {
private static JedisCluster jedisCluster;
void init() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(20);
config.setMaxIdle(2);
//創建節點
HostAndPort hp0 = new HostAndPort("192.168.21.171", 7000);
HostAndPort hp1 = new HostAndPort("192.168.21.171", 7001);
HostAndPort hp2 = new HostAndPort("192.168.21.171", 7002);
HostAndPort hp3 = new HostAndPort("192.168.21.171", 7003);
HostAndPort hp4 = new HostAndPort("192.168.21.171", 7004);
HostAndPort hp5 = new HostAndPort("192.168.21.171", 7005);
Set<HostAndPort> hps = new HashSet<HostAndPort>();
hps.add(hp0);
hps.add(hp1);
hps.add(hp2);
hps.add(hp3);
hps.add(hp4);
hps.add(hp5);
// 超時,最大的轉發數,最大鏈接數,最小鏈接數都會影響到集羣
jedisCluster = new JedisCluster(hps, 5000, 10, config);
}
public static void main(String[] args) throws InterruptedException {
final redisClusterConcurrent redisConcurrent = new redisClusterConcurrent();
redisConcurrent.init();
final AtomicLong counter = new AtomicLong(0);
final AtomicBoolean stopFlag = new AtomicBoolean(false);
final int threadCount = 1000;
for (int i = 0; i < threadCount; i++) {
final String sss = i + "";
new Thread(new Runnable() {
@Override
public void run() {
while (!stopFlag.get()) {
jedisCluster.set(sss, "aaasasdasdasdasdasdasdasdasdasdasdasdasdasaaaaaaaaaaaaaaaaaa");
counter.incrementAndGet();
}
}
}).start();
}
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.err.println("*** stop client ***");
stopFlag.set(true);
}
});
long startTime = System.currentTimeMillis();
while (!stopFlag.get()) {
Thread.sleep(1000);
final long count = counter.get();
long currentTime = System.currentTimeMillis();
long qps = count * 1000 / (currentTime - startTime);
System.out.println("qps=" + qps);
if ((currentTime - startTime) / 1000 > 10) {
counter.set(0);
startTime = currentTime;
System.out.println("reset counter");
}
}
}
}
創建一個JedisCluster,JedisCluster封裝了redis的命令,這樣就可以直接調用操作redis。測試的qps大概4萬左右,和ShardedJedisPool差不多,存儲100個數,可能節點1、5一樣,2、4的一樣,但是每一個節點的數據都不會超過100個,按一種算法去算,當一個節點掛了,並不會影響程序的正常使用,當剩下2個節點後,程序會報錯,這樣保證了高可用高併發性。