问题引入: 每次操作redis都会频繁创建和关闭链接 资源浪费 并且性能不好, 所以我们需要连接池 类似数据库连接一样.
一. 创建jedis.properties配置文件
host=localhost
port=6379
maxIdle=10
maxTotal=50
二. 编写工具类
public class JedisUtil {
private static JedisPool jedisPool = null;
static {
InputStream resourceAsStream = JedisUtil.class.getClassLoader().getResourceAsStream("jedis.properties");
Properties properties = new Properties();
try {
properties.load(resourceAsStream);
String host = properties.getProperty("host");
String port = properties.getProperty("port");
String maxIdle = properties.getProperty("maxIdle");
String maxTotal = properties.getProperty("maxTotal");
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
// 最大空闲数
jedisPoolConfig.setMaxIdle(Integer.valueOf(maxIdle));
// 最大连接数
jedisPoolConfig.setMaxTotal(Integer.valueOf(maxTotal));
jedisPool = new JedisPool(jedisPoolConfig,host,Integer.valueOf(port));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 获得Jedis
* @return
*/
public static Jedis getJedis(){
return jedisPool.getResource();
}
/**
* 释放资源
* @param jedis
*/
public static void closeJedis(Jedis jedis){
jedis.close();
}
}
三. 测试
@Test
public void testPool(){
Jedis jedis = JedisUtil.getJedis();
jedis.set("name2","aaaabbb");
JedisUtil.closeJedis(jedis);
}