创建JedisPool代码
// volatile 修饰private static volatile JedisPool jedisPool = null;
private JedisPoolUtils(){
}
public static JedisPool getJedisPoolInstance() {
// 使用双重检查创建单例
if(null == jedisPool) {
synchronized (JedisPoolUtils.class) {
if(null == jedisPool) {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(10);
poolConfig.setMaxIdle(10);
poolConfig.setMinIdle(2);
poolConfig.setMaxWaitMillis(30*1000);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
poolConfig.setTimeBetweenEvictionRunsMillis(10*1000);
poolConfig.setMinEvictableIdleTimeMillis(30*1000);
poolConfig.setNumTestsPerEvictionRun(-1);
jedisPool = new JedisPool(poolConfig,"localhost",6379);
}
}
}
return jedisPool;
}
实例创建和释放大致流程解析
根据流程进行源码解析 创建过程
使用pool.getResource()进行Jedis实例的创建。
//org.apache.commons.pool2.impl.GenericObjectPool#borrowObject(long)public T borrowObject(final long borrowMaxWaitMillis) throws Exception {
final boolean blockWhenExhausted = getBlockWhenExhausted();
PooledObject<T> p = null;
boolean create;
final long waitTime = System.currentTimeMillis();
while (p == null) {
create = false;
// 从空闲队列中获取
p = idleObjects.pollFirst();
if (p == null) {
// 创建实例
p = create();
if (p != null) {
create = true;
}
}
// 吃资源是否耗尽
if (blockWhenExhausted) {
if (p == null) {
// 等待时间小于0
if (borrowMaxWaitMillis < 0) {
p = idleObjects.takeFirst();
} else {
p = idleObjects.pollFirst(borrowMaxWaitMillis,
TimeUnit.MILLISECONDS);
}
}
if (p == null) {
throw new NoSuchElementException(
"Timeout waiting for idle object");
}
} else {
if (p == null) {
throw new NoSuchElementException("Pool exhausted");
}
}
if (!p.allocate()) {
p = null;
}
if (p != null) {
try {
// 重新初始化要由池返回的实例。
factory.activateObject(p);
} catch (final Exception e) {
}
}
}
updateStatsBorrow(p, System.currentTimeMillis() - waitTime);
return p.getObject();
}
释放过程