1 Redis连接池构建&代码解析
1-1 Redis连接池是什么?
连接池嘛,保存着连接咯。这点和mysql一样。我们可以设置连接池的参数连接数,校验等等,像下面的配置:
#redis
# 最大连接数
redis.max.total=20
# 在Jedis连接池里最大的状态为空闲(idle)的Jedis实例的个数
redis.max.idle=10
# 在Jedis连接池里最小的状态为空闲(idle)的Jedis实例的个数
redis.min.idle=2
# 从Jedis连接池里拿取一个实例时是否要进行验证操作 如果为true 则拿到的实例一定是可用的
redis.test.borrow=true
# 还给Jedis连接池的实例时是否要进行验证操作 如果为true 则还的的实例一定是可用的
redis.test.return=true
# ip
redis.ip=127.0.0.1
# port
redis.port=6379
怎么读配置,方法很多哪个顺眼用哪个。拿到配置后,初始化连接池:
private static void initPool() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxTotal);
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);
config.setTestOnBorrow(testOnBorrow);
config.setTestOnReturn(testOnReturn);
// 连接耗尽的时候师傅阻塞 false:抛异常 true: 阻塞直到超时
config.setBlockWhenExhausted(true);
pool = new JedisPool(config, redisIp, redisPort, 1000*2);
}
static {
initPool();
}
有了连接池,就可以从连接池里拿连接,还连接了:
// Jedis 连接池
private static JedisPool pool;
public static Jedis getJedis() {
return pool.getResource();
}
public static void returnBreakenResource(Jedis jedis) {
pool.returnBrokenResource(jedis);
}
public static void returnResource(Jedis jedis) {
pool.returnResource(jedis);
}
2 Jedis api封装
2-1 Jedis api封装了什么鬼东西?
当然是操作数据库的方法咯。鉴于操作的对象是Redis数据库,结合上回说的Redis常用命令,想下基本的方法有:根据key获取value的,新增记录的,记录可以有有效期,所以来个设置新增有效记录的,有效期可以新增自然也可以重设,于是有了重设key有效期的,最后来个删除记录的,这样算下来五个方法:
@Slf4j
public class RedisPoolUtil {
public static String get (String key) {
Jedis jedis = null;
String result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.get(key);
} catch (Exception e) {
log.error("get error! key:{} ", key, e);
RedisPool.returnBreakenResource(jedis);
return result;
}
RedisPool.returnResource(jedis);
return result;
}
public static String set (String key, String value) {
Jedis jedis = null;
String result = null;
try {
jedis = RedisPool.getJedis();
result =