Skip to content

Instantly share code, notes, and snippets.

@yayj
Created September 27, 2016 04:05
Show Gist options
  • Save yayj/854f21cfa318e36eddb3ab07fc6855dd to your computer and use it in GitHub Desktop.
Save yayj/854f21cfa318e36eddb3ab07fc6855dd to your computer and use it in GitHub Desktop.
Jedis with ARM
public class CloseableJedis implements AutoCloseable {
private final Jedis delegate;
private final JedisPool pool;
private boolean broken = false;
public CloseableJedis(JedisPool pool) {
this.pool = pool;
delegate = pool.getResource();
}
public void setBroken() {
broken = true;
}
public Jedis get() {
return delegate;
}
@Override
public void close() throws JedisException {
if (broken) {
pool.returnBrokenResource(delegate);
} else {
pool.returnResource(delegate);
}
}
}
public class Utils {
public static <T> T withJedis(JedisPool pool, final Function<Jedis, T> func) {
try (CloseableJedis connection = new CloseableJedis(pool)) {
return new Function<CloseableJedis, T>() {
@Override
public T apply(CloseableJedis input) {
try {
return func.apply(input.get());
} catch (JedisConnectionException e) {
input.setBroken();
throw e;
}
}
}.apply(connection);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment