最近在使用jedis工程中,由于一些原因,使用的仍是较低版本的jedis版本的。使用jedis时图省事,直接通过new 一个jedis的对象使用。之后出现了ArrayIndexOutOfBoundsException的错误:
具体为:
追踪源代码发现是write方法中通过递增count,向缓存字节数组中写入数据时出现的ArrayIndexOutOfBoundsException。
public RedisOutputStream(final OutputStream out) {
this(out, 8192);
}
public RedisOutputStream(final OutputStream out) {
this(out, 8192);
}
private void flushBuffer() throws IOException {
if (count > 0) {
out.write(buf, 0, count);
count = 0;
}
}
public void write(final byte b) throws IOException {
buf[count++] = b;
if (count == buf.length) {
flushBuffer();
}
}
在flush时的时候一旦出错,且源码并未catch,导致count不会清0,之后就会一直报越界的错误。新版本的jedis应该已经修复此错误。另外,也可以参照网上的一些jedis pool的方法,来主动catch这个错误:
public static Set<String> getSetData(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
Set<String> set = jedis.smembers(key);
return set;
} catch(Exception e){
if(jedis != null) {
jedisPool.returnBrokenResource(jedis);
}
logger.error("ERROR_Redis| getSetData Exception! key=" + key ,e);
return null;
} finally{
if(jedis != null){
jedisPool.returnResource(jedis);
jedis = null;
}
}
}