基于连接池获取连接
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
使用配置文件优化Jedis连接池,
文章展示了如何将Jedis连接池的配置从硬编码改为从配置文件中读取,包括设置最大连接数、最大活动连接数以及主机和端口信息,以实现更灵活和可维护的代码结构。
474

被折叠的 条评论
为什么被折叠?



