基于连接池获取连接
public class JedisUtils {
public static Jedis getJedis(){
JedisPoolConfig jpc = new JedisPoolConfig();
jpc.setMaxTotal(30);//最大连接数量
jpc.setMaxIdle(10);//最大活动数量
String host = "127.0.0.1";
int port = 6379;
JedisPool jp = new JedisPool(jpc,host,port);
return jp.getResource();
}
public static void main(String[] args) {
//测试
JedisUtils.getJedis();
}
}
//Jedis jedis = new Jedis("127.0.0.1", 6379);
Jedis jedis = JedisUtils.getJedis();
添加配置文件后 改良为:
public class JedisUtils {
private static JedisPool jp = null;
private static String host = null;
private static int port;
private static int maxTotal;
private static int maxIdle;
static {
ResourceBundle rb = ResourceBundle.getBundle("redis");
host = rb.getString("redis.host");
port = Integer.parseInt(rb.getString("redis.port"));
maxTotal = Integer.parseInt(rb.getString("redis.maxTotal"));
maxIdle = Integer.parseInt(rb.getString("redis.maxIdle"));
JedisPoolConfig jpc = new JedisPoolConfig();
jpc.setMaxTotal(maxTotal);
jpc.setMaxIdle(maxIdle);
jp = new JedisPool(jpc,host,port);
}
public static Jedis getJedis(){
return jp.getResource();
}
public static void main(String[] args){
JedisUtils.getJedis();
}
}
配置文件:
redis.host=127.0.0.1
redis.port=6379
redis.maxTotal=30
redis.maxIdle=10