private static void exampleUseofSyncInPipeline (ConnectionSpec connectionSpec) {
// Note that we are using a JRedisPipeline reference and not a generic
// JRedisFuture here -- this exposes the additional
JRedisPipeline pipeline = new JRedisPipeline(connectionSpec);
/*
* Alright, so a hokey example of situations where we would like to
* asynchronously pipeline a bunch of commands, and then at various point in
* the process need to sync up with redis and get values before continuing.
*
* Obviously we can do this using JRedisFuture as well by calling get() on the
* returned Future object, but the sync() method may be enhanced in future to
* provide additional features. Regardless, it does some of the boiler plate
* ExecutionException handling code so its a bit prettier.
*/
try {
long start = System.currentTimeMillis();
/* a sequence of asynchronous calls */
pipeline.ping();
pipeline.flushdb();
Random rand = new Random();
byte[] data = new byte[8];
for(int i=0; i<1000000; i++){
rand.nextBytes(data);
pipeline.lpush("my-list", data);
}
/*
* switch to synchronous semantics
* the following call will block until
* all the responses for above + the llen()
* itself have been received.
*/
long llen = pipeline.sync().llen("my-list");
String cntrKey = "my-cntr";
for(int i=0; i<100000; i++) {
pipeline.incr(cntrKey);
}
/* sync call */
long cntr = toLong (pipeline.sync().get(cntrKey));
for(int i=0; i<100000; i++){
pipeline.set("random:"+i, "value:" + rand.nextInt());
}
/* sync call */
String randomVal = toStr (pipeline.sync().get("random:"+999));
pipeline.flushdb();
System.out.format ("end using sync() = %d msec\n", System.currentTimeMillis() - start);
System.out.format("%s => %d\n", cntrKey, cntr);
System.out.format("%s => %s\n", "random:"+999, randomVal);
System.out.format("%s has %s items\n", "my-list", llen);
}
catch (RedisException e) {
Log.problem("RedisException: " + e);
}
finally{
pipeline.sync().quit();
Log.log("shutting down.");
}
}