Skip to content

Instantly share code, notes, and snippets.

@daschl
Created January 24, 2014 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daschl/8600479 to your computer and use it in GitHub Desktop.
Save daschl/8600479 to your computer and use it in GitHub Desktop.
Incr with default ;)
import com.couchbase.client.CouchbaseClient;
import com.couchbase.client.internal.HttpCompletionListener;
import com.couchbase.client.internal.HttpFuture;
import com.couchbase.client.internal.ViewFuture;
import com.couchbase.client.protocol.views.*;
import net.spy.memcached.internal.OperationFuture;
import net.spy.memcached.ops.Mutator;
import net.spy.memcached.ops.Operation;
import net.spy.memcached.ops.OperationCallback;
import net.spy.memcached.ops.OperationStatus;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String... args) throws Exception {
final MyCouchbaseClient client = new MyCouchbaseClient(
Arrays.asList(new URI("http://127.0.0.1:8091/pools")),
"default",
""
);
// increase by 10 with a default of 2
// first time it is called the value will be 2.
// second time its called it will be 12 and so on.
OperationFuture<Long> mykey = client.asyncIncr("mykey", 10, 2, 0);
mykey.get();
System.out.println(client.get("mykey"));
client.shutdown();
}
static class MyCouchbaseClient extends CouchbaseClient {
MyCouchbaseClient(List<URI> baseList, String bucketName, String pwd) throws IOException {
super(baseList, bucketName, pwd);
}
public OperationFuture<Long> asyncIncr(String key, long by, long def, int exp) {
return asyncMutate(Mutator.incr, key, by, def, exp);
}
/**
* 1:1 copied from MemcachedClient because it has private access. gotta fix this in a future release.
*/
private OperationFuture<Long> asyncMutate(Mutator m, String key, long by,
long def, int exp) {
final CountDownLatch latch = new CountDownLatch(1);
final OperationFuture<Long> rv =
new OperationFuture<Long>(key, latch, operationTimeout, executorService);
Operation op = opFact.mutate(m, key, by, def, exp,
new OperationCallback() {
@Override
public void receivedStatus(OperationStatus s) {
rv.set(new Long(s.isSuccess() ? s.getMessage() : "-1"), s);
}
@Override
public void complete() {
latch.countDown();
rv.signalComplete();
}
});
mconn.enqueueOperation(key, op);
rv.setOperation(op);
return rv;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment