Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/main/java/redis/clients/jedis/JedisPool.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package redis.clients.jedis;

import java.net.URI;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocketFactory;
Expand Down Expand Up @@ -392,4 +394,17 @@ public void returnResource(final Jedis resource) {
}
}
}

public void withJedisDo(Consumer<Jedis> consumer) {
try (Jedis jedis = getResource()) {
consumer.accept(jedis);
}
}

public <K> K withJedisGet(Function<Jedis, K> function) {
try (Jedis jedis = getResource()) {
return function.apply(jedis);
}
}

}
28 changes: 28 additions & 0 deletions src/test/java/redis/clients/jedis/JedisPoolTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
Expand Down Expand Up @@ -453,4 +455,30 @@ public void testResetValidCredentials() {
}
}
}

@Test
public void testWithJedisDo() {
try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort())) {
pool.withJedisDo(jedis -> {
jedis.auth("foobared");
assertEquals(jedis.getClient().getHostAndPort().getHost(), hnp.getHost());
assertEquals(jedis.getClient().getHostAndPort().getPort(), hnp.getPort());
assertNotNull(jedis.time());
});
}
}

@Test
public void testWithJedisGet() {
try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort())) {
List<String> result = pool.withJedisGet(jedis -> {
jedis.auth("foobared");
assertEquals(jedis.getClient().getHostAndPort().getHost(), hnp.getHost());
assertEquals(jedis.getClient().getHostAndPort().getPort(), hnp.getPort());
return jedis.time();
});
assertNotNull(result);
}
}

}