Skip to content

Instantly share code, notes, and snippets.

@AlexYangYu
Created April 28, 2013 06:52
Show Gist options
  • Save AlexYangYu/5476137 to your computer and use it in GitHub Desktop.
Save AlexYangYu/5476137 to your computer and use it in GitHub Desktop.
Use asynchbase to get or create an id for key.
package me.alexyang.deferred;
import com.stumbleupon.async.Callback;
import com.stumbleupon.async.Deferred;
import java.util.ArrayList;
import org.hbase.async.Bytes;
import org.hbase.async.GetRequest;
import org.hbase.async.HBaseClient;
import org.hbase.async.KeyValue;
import org.hbase.async.PutRequest;
/**
*
* @author Alex Yang <alex890714@gmail.com>
*/
public class TestDeferred {
public static void main(String[] args) throws Exception {
final String table = "test";
final String rowKey = "key";
HBaseClient hbase = new HBaseClient("centos-pd.alexyang.me");
hbase.ensureTableExists("test").joinUninterruptibly();
GetRequest getRequest = new GetRequest(table, rowKey);
getRequest.family("id").qualifier("id");
Deferred<ArrayList<KeyValue>> getIdDeferred;
getIdDeferred = hbase.get(getRequest);
Deferred<byte[]> getIdResult = getIdDeferred.
addCallback(new GetIdResultHandler()).
addCallbacks(new DoNothingHandler(), new CreateIdHandler(hbase));
System.out.println(Bytes.getInt(getIdResult.joinUninterruptibly()));
hbase.shutdown().joinUninterruptibly();
}
}
class GetIdResultHandler implements Callback<byte[], ArrayList<KeyValue>> {
public byte[] call(ArrayList<KeyValue> t) throws Exception {
System.out.println("GetIdResultHandler:call()");
if (null == t || 0 == t.size()) {
throw new Exception("No ID.");
}
return t.get(0).value();
}
}
class CreateIdHandler implements Callback<byte[], Exception> {
private final HBaseClient hbase;
public CreateIdHandler(HBaseClient client) {
hbase = client;
}
public byte[] call(Exception t) throws Exception {
System.out.println("CreateIdHandler:call()");
byte[] value = Bytes.fromInt(1);
PutRequest putRequest = new PutRequest(
"test".getBytes(), "key".getBytes(), "id".getBytes(),
"id".getBytes(), value);
hbase.put(putRequest).joinUninterruptibly();
GetRequest getRequest = new GetRequest("test", "key");
getRequest.family("id").qualifier("id");
ArrayList<KeyValue> arrs = hbase.get(getRequest).joinUninterruptibly();
if (null == arrs || 0 == arrs.size()) {
return null;
}
return arrs.get(0).value();
}
}
class DoNothingHandler implements Callback<byte[], byte[]> {
public byte[] call(byte[] t) throws Exception {
return t;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment