Created
February 14, 2012 22:58
-
-
Save jasobrown/1831396 to your computer and use it in GitHub Desktop.
An example of using astyanax, a Java client for Cassandra (excerpt from http://slidesha.re/wkf57g)
This file contains hidden or 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
| public class AstyanaxSample { | |
| /** entry point for the cluster; read the docs at https://github.com/Netflix/astyanax/wiki/Getting-Started */ | |
| private static final Keyspace keyspace = null; //null used for compilation; don't try this at home | |
| /** declare/define the column family object */ | |
| private static final ColumnFamily<String, MyCompositeColumn> ALLOCS_COLUMN_FAMILY = | |
| new ColumnFamily<String, MyCompositeColumn>("cust_allocs", StringSerializer.get(), | |
| new AnnotatedCompositeSerializer<MyCompositeColumn>(MyCompositeColumn.class)); | |
| /** annotated class to represent the composite column type for an allocation */ | |
| private static class MyCompositeColumn { | |
| @Component(ordinal = 0) | |
| private Integer testId; | |
| @Component(ordinal = 1) | |
| private String field; | |
| public MyCompositeColumn() { } | |
| public Integer getTestId() { return testId; } | |
| public void setTestId(Integer testId) { this.testId = testId; } | |
| public String getField() { return field; } | |
| public void setField(String field) { this.field = field; } | |
| } | |
| /* get all allocations for a customer */ | |
| public List<Allocation> get(Long customerId){ | |
| try{ | |
| /* construct the query and send it to cassandra */ | |
| ColumnList<MyCompositeColumn> columns = keyspace | |
| .prepareQuery(ALLOCS_COLUMN_FAMILY) | |
| .getKey(custIdToKey(customerId)) | |
| .execute() | |
| .getResult(); | |
| return readColumns(columns); | |
| } catch (Exception e){ | |
| // don't do this at home | |
| return null; | |
| } | |
| /* pull data out of the columns and instantiate/populate the Allocation list */ | |
| private List<Allocation> readColumns(ColumnList<MyCompositeColumn> columns){ | |
| List<Allocation> list = new ArrayList<Allocation>(); | |
| Allocation cur = null; | |
| for(Column<MyCompositeColumn> column : columns){ | |
| Integer testId = column.getName().testId; | |
| if(cur == null || !cur.getTestID().equals(testId)){ | |
| cur = new Allocation(); | |
| cur.setTestID(testId); | |
| list.add(cur); | |
| } | |
| String field = column.getName().field; | |
| if(field.equals("cell")) | |
| cur.setCell(Integer.valueOf(column.getIntegerValue())); | |
| else if(field.equals("enabled")) | |
| cur.setEnabled(column.getStringValue()); | |
| } | |
| return list; | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Comments intentionally short to not get in the way of the code.