add checks when server closes idle connections

This commit is contained in:
Jonathan Leibiusky
2010-11-30 12:27:22 -03:00
parent efb27de003
commit 81ec9f8af3
3 changed files with 38 additions and 18 deletions

View File

@@ -16,9 +16,11 @@
package redis.clients.util;
import redis.clients.jedis.JedisException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.*;
import redis.clients.jedis.JedisException;
public class RedisInputStream extends FilterInputStream {
@@ -38,9 +40,9 @@ public class RedisInputStream extends FilterInputStream {
this(in, 8192);
}
public byte readByte () throws IOException {
if(count == limit) {
fill ();
public byte readByte() throws IOException {
if (count == limit) {
fill();
}
return buf[count++];
@@ -53,19 +55,19 @@ public class RedisInputStream extends FilterInputStream {
try {
while (true) {
if(count == limit) {
fill ();
if (count == limit) {
fill();
}
if(limit == -1)
if (limit == -1)
break;
b = buf[count++];
if (b == '\r') {
if(count == limit) {
fill ();
if (count == limit) {
fill();
}
if(limit == -1) {
if (limit == -1) {
sb.append((char) b);
break;
}
@@ -83,14 +85,19 @@ public class RedisInputStream extends FilterInputStream {
} catch (IOException e) {
throw new JedisException(e);
}
return sb.toString();
String reply = sb.toString();
if (reply.isEmpty()) {
throw new JedisException(
"It seems like server has closed the connection.");
}
return reply;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if(count == limit) {
fill ();
if(limit == -1)
if (count == limit) {
fill();
if (limit == -1)
return -1;
}
final int length = Math.min(limit - count, len);
@@ -99,7 +106,7 @@ public class RedisInputStream extends FilterInputStream {
return length;
}
private void fill () throws IOException {
private void fill() throws IOException {
limit = in.read(buf);
count = 0;
}

View File

@@ -6,6 +6,7 @@ import java.util.Map;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisException;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.Protocol;
import redis.clients.jedis.tests.commands.JedisCommandTestBase;
@@ -41,4 +42,16 @@ public class JedisTest extends JedisCommandTestBase {
Jedis jedis = new Jedis(shardInfo);
jedis.get("foo");
}
}
@Test(expected = JedisException.class)
public void timeoutConnection() throws Exception {
jedis = new Jedis("localhost", 6379, 15000);
jedis.auth("foobared");
jedis.configSet("timeout", "1");
// we need to sleep a long time since redis check for idle connections
// every 10 seconds or so
Thread.sleep(20000);
jedis.hmget("foobar", "foo");
jedis.configSet("timeout", "300");
}
}

View File

@@ -5,6 +5,6 @@ import org.junit.Test;
public class ConnectionHandlingCommandsTest extends JedisCommandTestBase {
@Test
public void quit() {
jedis.quit();
jedis.quit();
}
}