Skip to content

Instantly share code, notes, and snippets.

@ingenthr
Created July 23, 2013 23:03
Show Gist options
  • Save ingenthr/6066922 to your computer and use it in GitHub Desktop.
Save ingenthr/6066922 to your computer and use it in GitHub Desktop.
Sample of looking up the node associated with a given key on Couchbase.
/**
* Copyright 2013, Couchbase, Inc. All rights reserved.
*/
package com.couchbase.demo.vbucketlookup;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.ConfigurationException;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.MemcachedNode;
import net.spy.memcached.NodeLocator;
import com.couchbase.client.CouchbaseClient;
/**
* Look up the node associated with a given vbucket.
*
* WARNING: This is intended ONLY as a diagnosis tool. In general
* an application should not be aware of the location a given data
* item is assigned to. Also, note that the configuration can change
* at any time, so the lookup you may do associated with a given key may
* be _invalid_ by the time you request the actual operation via the
* client object method.
*
*/
public class VbucketLookup {
public static void main(String args[]) {
if (args.length < 2) {
System.err.println("Usage: java -jar spyHashTest.jar http://my.server:8091 keyToFind");
System.exit(1);
}
URI bootUri = null;
try {
bootUri = new URI(args[0]);
} catch (URISyntaxException ex) {
Logger.getLogger(VbucketLookup.class.getName()).log(Level.SEVERE, "Invalid URI specified: " + args[1] + "\nCannot continue.", ex);
}
VbucketLookup looker = new VbucketLookup();
looker.lookupKey(bootUri, args[1]);
}
private void lookupKey(URI bootstrap, String key) {
String bucketName = "default";
ArrayList<URI> uriList = new ArrayList();
uriList.add(bootstrap);
MemcachedClient cbc = null;
try {
cbc = new CouchbaseClient(uriList, bucketName, "", "");
} catch (IOException ex) {
Logger.getLogger(VbucketLookup.class.getName()).log(Level.SEVERE, "Could not connect to server. IOException received.", ex);
System.err.println(ex.getCause());
}
NodeLocator nodeLocator = cbc.getNodeLocator();
nodeLocator.getReadonlyCopy();
MemcachedNode primary = nodeLocator.getPrimary(key);
String nodeString = primary.toString();
String nodeSubstr = nodeString.substring(nodeString.indexOf("/") + 1, nodeString.indexOf(","));
System.out.println(key + " hashes to node " + nodeSubstr + " for " + bucketName + " bucket.");
cbc.shutdown(10, TimeUnit.SECONDS);
}
}
@ingenthr
Copy link
Author

Output like:
Matt hashes to node 127.0.0.1:11210 for default bucket.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment