redis哨兵模式连接代码
package com.zx.zhuangxiu.cache;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import java.util.HashSet;
import java.util.Set;
public class RedisPool {
private static JedisSentinelPool pool = null;;//jedis连接池
private static int maxTotal = 20;//最大连接数
private static int maxIdle = 10;//最大空闲连接数
private static int minIdle = 5;//最小空闲连接数
private static boolean testOnBorrow = true;//在取连接时测试连接的可用性
private static boolean testOnReturn = false;//再还连接时不测试连接的可用性
static {
initPool();//初始化连接池
}
public static Jedis getJedis(){
return pool.getResource();
}
public static void close(Jedis jedis){
jedis.close();
}
private static void initPool(){
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxTotal);
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);
config.setTestOnBorrow(testOnBorrow);
config.setTestOnReturn(testOnReturn);
config.setBlockWhenExhausted(true);
String masterName = "myMaster";
Set<String> sentinels = new HashSet<String>();
sentinels.add("192.168.204.133:26379");
//sentinels.add("192.168.204.134:26379");
pool = new JedisSentinelPool(masterName, sentinels, config);
}
}
测试
import com.zx.zhuangxiu.cache.RedisPool;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class tt {
@Test
public void ee(){
RedisPool.getJedis().set("aa","bb");
String ee= RedisPool.getJedis().get("aa");
System.out.println(ee);
}
}
还没有评论,来说两句吧...