Created
April 17, 2012 13:58
-
-
Save swaroopch/2406141 to your computer and use it in GitHub Desktop.
Testing Jedis (Java Redis API) for parallel requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://github.com/xetorthio/jedis | |
import redis.clients.jedis.Jedis; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.Future; | |
import java.util.concurrent.atomic.AtomicInteger; | |
public class TestJedis { | |
public static void main(String[] args) throws ExecutionException, InterruptedException { | |
testSequential(); | |
testParallel(); | |
} | |
public static void testSequential() throws InterruptedException { | |
final Jedis jedis = new Jedis("127.0.0.1", 6379); | |
jedis.set("abc", Long.toString(0)); | |
for (int i = 0; i < 500; i++) { | |
jedis.incrBy("abc", i); | |
} | |
System.out.println("Done: " + jedis.get("abc")); | |
} | |
/** | |
* Exception in thread "main" java.util.concurrent.ExecutionException: redis.clients.jedis.exceptions.JedisConnectionException: It seems like server has closed the connection. | |
*/ | |
public static void testParallel() throws ExecutionException, InterruptedException { | |
final Jedis jedis = new Jedis("127.0.0.1", 6379); | |
jedis.set("abc", "0"); | |
ExecutorService executorService = Executors.newFixedThreadPool(500); | |
List<Future<Runnable>> futureList = new ArrayList<Future<Runnable>>(); | |
for (final AtomicInteger i = new AtomicInteger(); i.get() < 500; i.getAndIncrement()) { | |
Future future = executorService.submit(new Runnable() { | |
@Override | |
public void run() { | |
jedis.incrBy("abc", i.get()); | |
System.out.println("Incremented by " + Integer.toString(i.get())); | |
} | |
}); | |
futureList.add(future); | |
} | |
for (Future<Runnable> future : futureList) { | |
future.get(); | |
} | |
System.out.println("Done: " + jedis.get("abc")); | |
} | |
//jedis.quit(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment