Write in front
see GitHub for all sample codes in this tutorial: https://github.com/selfconzrr/Redis_Learning
Why close the connection?
For example, the following code:
for(int i = 2000; i < 3000; i++) {
Jedis jedis = redisDao.getJedis();
jedis.set("user:" + i, jedis.toString());
System.out.println(jedis);
set.add(jedis.toString());
}
in the above code, when you cycle to 600 times, an error will be reported that you can't get the connection, and 600 is exactly the number of connections in the configuration; and the jedis connection will not be automatically released after the end of use (because after an error is reported, you can request this method again, and you can't get a connection). If you add
jedis.close();
.
jedis version 3.0, using jedis.close Method () closes the connection. The source code of close() is as follows:
@Override
public void close() {
if (dataSource != null) {
if (client.isBroken()) {
this.dataSource.returnBrokenResource(this);
} else {
this.dataSource.returnResource(this);
}
} else {
client.close();
}
}
. If the Jedis instance obtained from Jedis pool (the dataSource member of Jedis not empty, that is, points.
Precautions for using Jedis returnResource:
returnResource() cannot be used in all cases.
The causes and cases are as follows:
while(true){
Jedis jedis = null;
boolean broken = false;
try {
jedis = jedisPool.getResource();
return jedisAction.action(jedis); //Template method
} catch (JedisException e) {
broken = handleJedisException(e);
throw e;
} finally {
closeResource(jedis, broken);
}
}
/**
* Handle jedisException, write log and return whether the connection is broken.
*/
protected boolean handleJedisException(JedisException jedisException) {
if (jedisException instanceof JedisConnectionException) {
logger.error("Redis connection " + jedisPool.getAddress() + " lost.", jedisException);
} else if (jedisException instanceof JedisDataException) {
if ((jedisException.getMessage() != null) && (jedisException.getMessage().indexOf("READONLY") != -1)) {
logger.error("Redis connection " + jedisPool.getAddress() + " are read-only slave.", jedisException);
} else {
// dataException, isBroken=false
return false;
}
} else {
logger.error("Jedis exception happen.", jedisException);
}
return true;
}
/**
* Return jedis connection to the pool, call different return methods depends on the conectionBroken status.
*/
protected void closeResource(Jedis jedis, boolean conectionBroken) {
try {
if (conectionBroken) {
jedisPool.returnBrokenResource(jedis);
} else {
jedisPool.returnResource(jedis);
}
} catch (Exception e) {
logger.error("return back jedis failed, will fore close the jedis.", e);
JedisUtils.destroyJedis(jedis);
}
}
- – be willing to share and make progress together
—–Any comments greatly appreciated
We sincerely welcome you to exchange and discuss! QQ:1138517609