Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save HeartSaVioR/2f7fa49e42163c83418a to your computer and use it in GitHub Desktop.
Save HeartSaVioR/2f7fa49e42163c83418a to your computer and use it in GitHub Desktop.
Testing ShardedJedisPool with try-with-resource
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestShardedJedisWithMultiThreaded {
private ShardedJedisPool pool;
public TestShardedJedisWithMultiThreaded() throws URISyntaxException {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(100);
config.setTestOnBorrow(true);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6380")));
shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6379")));
pool = new ShardedJedisPool(config, shards);
}
public void startTest() throws InterruptedException {
//ExecutorService es = Executors.newFixedThreadPool(5);
ExecutorService es = Executors.newFixedThreadPool(20);
for (int i = 0 ; i < 100 ; i++) {
es.execute(new Worker(pool));
}
es.shutdown();
}
class Worker extends Thread {
private ShardedJedisPool pool;
public Worker(ShardedJedisPool pool) {
this.pool = pool;
}
@Override
public void run() {
try {
sleep(100);
} catch (InterruptedException e) {
}
System.out.println(this.getName() + " : about to zadd...");
try (ShardedJedis shJedis = pool.getResource()) {
shJedis.zadd("Hello", 2, "World");
System.out.println(this.getName() + " : zadd ok...");
} catch (JedisConnectionException e) {
System.out.println(this.getName() + " : fail to get connection...");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment