一、jedis是什么?
Jedis是redis的java版本的客户端实现,使用Jedis提供的Java API对Redis进行操作,是Redis官方推崇的方式;并且,使用Jedis提供的对Redis的支持也最为灵活、全面;不足之处,就是编码复杂度较高。
二、为什么要使用JedisPool
1,获取Jedis实例需要从JedisPool中获取
2,用完Jedis实例需要返还给JedisPool
3,如果Jedis在使用过程中出错,则也需要还给JedisPool
三、JedisPool的使用
1、创建Jedispool连接池对象
public JedisPool redisPoolFactory() throws Exception{
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
// jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
// 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
jedisPoolConfig.setTestOnBorrow(true);
jedisPoolConfig.setTestOnReturn(true);
// 是否启用pool的jmx管理功能, 默认true
jedisPoolConfig.setJmxEnabled(true);
if ("".equals(password)) password = null;
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
log.info("JedisPool注入成功!!");
log.info("redis地址:" + host + ":" + port);
return jedisPool;
}
2、使用JedisPool创建jedis对象,使用后关闭
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis//相关操作;
} catch (Exception e) {
log.error(e.getMessage());
return false;
} finally {
if (jedis != null) {
jedis.close();
}
}