서버는 cassandra 2.0.1로 테스트했다.
1. data sax cql, jdbc driver (code google)
pom.xml
<dependency>
<groupId>org.apache.cassandra</groupId>
<artifactId>cassandra-thrift</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>2.0.0-beta2</version>
</dependency>
code
package com.google.cassandra.client;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.cassandra.cql.jdbc.CassandraStatementExtras;
import org.apache.cassandra.thrift.ConsistencyLevel;
public class CQLTest {
/*
*
CREATE TABLE cf10 (
key text,
number text,
name text,
PRIMARY KEY (key, number)
) WITH COMPACT STORAGE AND
bloom_filter_fp_chance=0.010000 AND
caching='KEYS_ONLY' AND
comment='' AND
dclocal_read_repair_chance=0.000000 AND
gc_grace_seconds=864000 AND
index_interval=128 AND
read_repair_chance=0.100000 AND
replicate_on_write='true' AND
populate_io_cache_on_flush='false' AND
default_time_to_live=0 AND
speculative_retry='NONE' AND
memtable_flush_period_in_ms=0 AND
compaction={'class': 'SizeTieredCompactionStrategy'} AND
compression={'sstable_compression': 'LZ4Compressor'};
cqlsh:userkeyspace> select * from cf10;
key | number | name
------+--------+------
row1 | 1 | Kim
row1 | 2 | Yu
row2 | 1 | Park
row2 | 2 | Choi
(4 rows)
*/
private static java.sql.Connection con = null;
public static void main(String[] args) throws Exception {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con = DriverManager.getConnection("jdbc:cassandra://localhost:9160/userkeyspace?consistency=ONE");
CQLTest sample = new CQLTest();
try {
sample.checkConsistency();
sample.create();
sample.insert();
sample.list();
sample.update();
sample.listUpdated();
sample.delete();
} catch (SQLException e) {
throw e;
}
}
public static final String KEY_SPACE_NAME = "userkeyspace";
public static final String COLUMN_FAMILY_NAME = "cf10";
public void checkConsistency() throws Exception {
Statement stmt = con.createStatement();
ConsistencyLevel cl = statementExtras(stmt).getConsistencyLevel();
System.out.println("consistency level : " + cl );
}
private CassandraStatementExtras statementExtras(Statement statement) throws Exception {
Class<?> cse = Class.forName("org.apache.cassandra.cql.jdbc.CassandraStatementExtras");
return (CassandraStatementExtras) statement.unwrap(cse);
}
public void create() throws SQLException {
drop();
String data = "create table IF NOT EXISTS " + COLUMN_FAMILY_NAME
+ " (key text, number text, name text, PRIMARY KEY (key, number)) WITH COMPACT STORAGE;";
Statement st = con.createStatement();
st.execute(data);
}
public void drop() throws SQLException {
String data = "drop table IF EXISTS " + COLUMN_FAMILY_NAME + ";";
Statement st = con.createStatement();
st.execute(data);
}
public void insert() throws SQLException {
String cql = "BEGIN BATCH \n"
+ "insert into " + COLUMN_FAMILY_NAME + " (key, number, name) values ('row1','1','Kim') \n"
+ "insert into " + COLUMN_FAMILY_NAME + " (key, number, name) values ('row1','2','Yu') \n"
+ "insert into " + COLUMN_FAMILY_NAME + " (key, number, name) values ('row2','1','Park') \n"
+ "insert into " + COLUMN_FAMILY_NAME + " (key, number, name) values ('row2','2','Choi') \n"
+ "APPLY BATCH;";
//String cql = "insert into " + COLUMN_FAMILY_NAME + " (key, number, name) values ('row1','1','Kim') ";
Statement st = con.createStatement();
st.executeUpdate(cql);
st.close();
/*
prepared statement code is not working in 1.2.5 cassandra -jdbc.. Caused by: InvalidRequestException(why:Invalid amount of bind variables)
https://code.google.com/a/apache-extras.org/p/cassandra-jdbc/issues/detail?id=93&thanks=93&ts=1383294323
String cql2 = "insert into " + COLUMN_FAMILY_NAME + " (key, number, name) values (?, ?, ?)";
PreparedStatement ps = con.prepareStatement(cql2);
ps.setString(1, "row1");
ps.setString(2, "1");
ps.setString(3, "Kim");
ps.executeUpdate(cql2);
ps.close();
*/
}
public void delete() throws SQLException {
String data = "truncate " + COLUMN_FAMILY_NAME ;
Statement st = con.createStatement();
st.executeUpdate(data);
}
public void update() throws SQLException {
String t = "update " + COLUMN_FAMILY_NAME + " set name='AAAA' where key='row1' and number = '1'";
Statement st = con.createStatement();
st.executeUpdate(t);
}
public void listUpdated() throws SQLException {
String t = "select * from " + COLUMN_FAMILY_NAME + " where key = 'row1' and number = '1'";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(t);
System.out.println("---------------");
while (rs.next()) {
System.out.println(" " + rs.getString("key"));
for (int j = 1; j < rs.getMetaData().getColumnCount() + 1; j++) {
System.out.println(" " + rs.getMetaData().getColumnName(j) + " : "
+ rs.getString(rs.getMetaData().getColumnName(j)));
}
}
}
public void list() throws SQLException {
String t = "select * from " + COLUMN_FAMILY_NAME;
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(t);
System.out.println("---------------");
while (rs.next()) {
System.out.println(" " + rs.getString("key"));
for (int j = 1; j < rs.getMetaData().getColumnCount() + 1; j++) {
System.out.println(" " + rs.getMetaData().getColumnName(j) + " : "
+ rs.getString(rs.getMetaData().getColumnName(j)));
}
}
}
}
prepared statement 테스트했는데, 에러가 난다....ㅠ
2. Thrift
pom.xml
<dependency>
<groupId>org.apache.cassandra</groupId>
<artifactId>cassandra-thrift</artifactId>
<version>2.0.1</version>
</dependency>
code
package com.google.cassandra.client;
import java.nio.ByteBuffer;
import java.util.List;
import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.ColumnParent;
import org.apache.cassandra.thrift.Compression;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.thrift.KeyRange;
import org.apache.cassandra.thrift.KeySlice;
import org.apache.cassandra.thrift.SlicePredicate;
import org.apache.cassandra.thrift.SliceRange;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
public class ThriftTest {
/*
cqlsh:userkeyspace> describe columnfamily cf11;
CREATE TABLE cf11 (
key text,
name text,
number text,
PRIMARY KEY (key)
) WITH COMPACT STORAGE AND
bloom_filter_fp_chance=0.010000 AND
caching='KEYS_ONLY' AND
comment='' AND
dclocal_read_repair_chance=0.000000 AND
gc_grace_seconds=864000 AND
index_interval=128 AND
read_repair_chance=0.100000 AND
replicate_on_write='true' AND
populate_io_cache_on_flush='false' AND
default_time_to_live=0 AND
speculative_retry='NONE' AND
memtable_flush_period_in_ms=0 AND
compaction={'class': 'SizeTieredCompactionStrategy'} AND
compression={'sstable_compression': 'LZ4Compressor'};
cqlsh:userkeyspace> select * from cf11;
key | name | number
------+------+--------
row1 | 1 | 2
(1 rows)
*/
public static void main(String[] args) throws Exception {
ThriftTest sample = new ThriftTest();
sample.getConfig();
sample.create();
sample.insert();
sample.list();
}
public static final String KEYSPACE_NAME = "userkeyspace";
public static final String ROW_KEY_NAME = "row1";
public static final String COLUMN_FAMILY_NAME = "cf11";
Cassandra.Client client;
TTransport tr;
public void getConfig() {
tr = new TFramedTransport(new TSocket("localhost", 9160));
TProtocol proto = new TBinaryProtocol(tr);
client = new Cassandra.Client(proto);
}
public void create() throws Exception {
tr.open();
String cql = "use " + KEYSPACE_NAME + ";";
client.execute_cql_query(ByteBuffer.wrap(cql.getBytes()), Compression.NONE);
cql = "drop table " + COLUMN_FAMILY_NAME + ";";
client.execute_cql_query(ByteBuffer.wrap(cql.getBytes()), Compression.NONE);
cql = "create columnfamily " + COLUMN_FAMILY_NAME + " (key text primary key, name text, number text);";
client.execute_cql_query(ByteBuffer.wrap(cql.getBytes()), Compression.NONE);
tr.close();
}
public void insert() throws Exception {
tr.open();
client.set_keyspace(KEYSPACE_NAME);
// insert data
long timestamp = System.currentTimeMillis();
Column nameColumn = new Column(ByteBuffer.wrap("name".getBytes()));
nameColumn.setValue(Long.toHexString(1).getBytes());
nameColumn.setTimestamp(timestamp);
Column numberColumn = new Column(ByteBuffer.wrap("number".getBytes()));
numberColumn.setValue(Long.toHexString(2).getBytes());
numberColumn.setTimestamp(timestamp);
ColumnParent columnParent = new ColumnParent(COLUMN_FAMILY_NAME);
client.insert(ByteBuffer.wrap(ROW_KEY_NAME.getBytes()), columnParent,nameColumn,ConsistencyLevel.ALL) ;
client.insert(ByteBuffer.wrap(ROW_KEY_NAME.getBytes()), columnParent,numberColumn,ConsistencyLevel.ALL);
tr.close();
}
public void list() throws Exception {
tr.open();
client.set_keyspace(KEYSPACE_NAME);
ColumnParent columnParent = new ColumnParent(COLUMN_FAMILY_NAME);
// make predicate
SlicePredicate predicate = new SlicePredicate();
predicate.setSlice_range(new SliceRange(ByteBuffer.wrap(new byte[0]), ByteBuffer.wrap(new byte[0]), false, 100));
List<ColumnOrSuperColumn> columnsByKey = client.get_slice(ByteBuffer.wrap(ROW_KEY_NAME.getBytes()), columnParent, predicate, ConsistencyLevel.ALL);
System.out.println(columnsByKey);
// list
KeyRange keyRange = new KeyRange(100);
keyRange.setStart_key(new byte[0]);
keyRange.setEnd_key(new byte[0]);
List<KeySlice> keySlices = client.get_range_slices(columnParent, predicate, keyRange, ConsistencyLevel.ONE);
System.out.println("size : " + keySlices.size());
for (KeySlice ks : keySlices) {
System.out.println("key : " + new String(ks.getKey()));
for (ColumnOrSuperColumn columns : ks.columns) {
System.out.println(" column name : " + new String(columns.getColumn().getName()) +
", value : " + new String(columns.getColumn().getValue()));
}
}
tr.close();
}
}
3. Hector
<dependency>
<groupId>me.prettyprint</groupId>
<artifactId>hector-core</artifactId>
<version>1.0-2</version>
</dependency>
package com.google.cassandra.client;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import me.prettyprint.cassandra.model.BasicColumnDefinition;
import me.prettyprint.cassandra.model.BasicColumnFamilyDefinition;
import me.prettyprint.cassandra.model.ConfigurableConsistencyLevel;
import me.prettyprint.cassandra.model.CqlQuery;
import me.prettyprint.cassandra.model.CqlRows;
import me.prettyprint.cassandra.model.RowImpl;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.cassandra.service.CassandraHostConfigurator;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.HConsistencyLevel;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.beans.ColumnSlice;
import me.prettyprint.hector.api.beans.HColumn;
import me.prettyprint.hector.api.beans.OrderedRows;
import me.prettyprint.hector.api.beans.Row;
import me.prettyprint.hector.api.ddl.ColumnIndexType;
import me.prettyprint.hector.api.ddl.ComparatorType;
import me.prettyprint.hector.api.factory.HFactory;
import me.prettyprint.hector.api.mutation.Mutator;
import me.prettyprint.hector.api.query.QueryResult;
import me.prettyprint.hector.api.query.RangeSlicesQuery;
public class HectorTest {
public static void main(String[] args) {
HectorTest sample = new HectorTest();
sample.getConfig();
sample.create();
sample.insert();
sample.read1();
sample.read2();
/*
CREATE TABLE cf6 (
key text,
name text,
number text,
PRIMARY KEY (key)
) WITH COMPACT STORAGE AND
bloom_filter_fp_chance=0.010000 AND
caching='KEYS_ONLY' AND
comment='' AND
dclocal_read_repair_chance=0.000000 AND
gc_grace_seconds=0 AND
index_interval=128 AND
read_repair_chance=0.000000 AND
replicate_on_write='false' AND
populate_io_cache_on_flush='false' AND
default_time_to_live=0 AND
speculative_retry='NONE' AND
memtable_flush_period_in_ms=0 AND
compaction={'class': 'SizeTieredCompactionStrategy'} AND
compression={'sstable_compression': 'LZ4Compressor'};
CREATE INDEX name_idx ON cf6 (name);
CREATE INDEX number_idx ON cf6 (number);
cqlsh:userkeyspace> select * from cf6;
(0 rows)
why? bug?
*/
}
Cluster cluster = null;
Keyspace keySpace = null;
BasicColumnFamilyDefinition columnFamilyDefinition = null;
public static final String KEY_SPACE_NAME = "userkeyspace";
public static final String COLUMN_FAMILY_NAME = "cf6";
public void getConfig() {
String hosts = "localhost:9160";
// connection pool : https://github.com/hector-client/hector/wiki/User-Guide
CassandraHostConfigurator cassandraHostConfigurator = new CassandraHostConfigurator(hosts);
cassandraHostConfigurator.setMaxActive(1);
cassandraHostConfigurator.setCassandraThriftSocketTimeout(3000);
cassandraHostConfigurator.setMaxWaitTimeWhenExhausted(4000);
cluster = HFactory.getOrCreateCluster("Test Cluster", cassandraHostConfigurator);
// basic case : not connection pool
//cluster = HFactory.getOrCreateCluster("Test Cluster", "localHost:9160");
// consistency level
ConfigurableConsistencyLevel configurableConsistencyLevel = new ConfigurableConsistencyLevel();
Map<String, HConsistencyLevel> clmap = new HashMap<String, HConsistencyLevel>();
clmap.put("MyColumnFamily", HConsistencyLevel.ONE);
configurableConsistencyLevel.setReadCfConsistencyLevels(clmap);
configurableConsistencyLevel.setWriteCfConsistencyLevels(clmap);
HFactory.createKeyspace(KEY_SPACE_NAME, cluster, configurableConsistencyLevel);
keySpace = HFactory.createKeyspace(KEY_SPACE_NAME, cluster);
}
public void create() {
cluster.dropColumnFamily(KEY_SPACE_NAME, COLUMN_FAMILY_NAME, true);
StringSerializer stringSerializer = StringSerializer.get();
// column definition
BasicColumnDefinition numberColumnDefinition = new BasicColumnDefinition();
numberColumnDefinition.setName(stringSerializer.toByteBuffer("number"));
numberColumnDefinition.setIndexName("number_idx");
numberColumnDefinition.setIndexType(ColumnIndexType.KEYS);
numberColumnDefinition.setValidationClass(ComparatorType.UTF8TYPE.getClassName());
BasicColumnDefinition nameColumnDefinition = new BasicColumnDefinition();
nameColumnDefinition.setName(stringSerializer.toByteBuffer("name"));
nameColumnDefinition.setIndexName("name_idx");
nameColumnDefinition.setIndexType(ColumnIndexType.KEYS);
nameColumnDefinition.setValidationClass(ComparatorType.UTF8TYPE.getClassName());
// column family (table) definition
columnFamilyDefinition = new BasicColumnFamilyDefinition();
columnFamilyDefinition.setKeyspaceName(KEY_SPACE_NAME);
columnFamilyDefinition.setName(COLUMN_FAMILY_NAME);
columnFamilyDefinition.setKeyValidationClass(ComparatorType.UTF8TYPE.getClassName());
columnFamilyDefinition.setComparatorType(ComparatorType.UTF8TYPE);
// adding column family to column.
columnFamilyDefinition.addColumnDefinition(numberColumnDefinition);
columnFamilyDefinition.addColumnDefinition(nameColumnDefinition);
cluster.addColumnFamily(columnFamilyDefinition);
assert columnFamilyDefinition != null;
}
public void insert() {
StringSerializer stringSerializer = StringSerializer.get();
Mutator<String> mutator = HFactory.createMutator(keySpace, stringSerializer);
// mutator insert
mutator.insert("row1", columnFamilyDefinition.getName(), HFactory.createStringColumn("1", "Kim"));
mutator.insert("row1", columnFamilyDefinition.getName(), HFactory.createStringColumn("2", "Park"));
mutator.insert("row1", columnFamilyDefinition.getName(), HFactory.createStringColumn("3", "Yun"));
// mutator batch
mutator.addInsertion("row2", columnFamilyDefinition.getName(), HFactory.createStringColumn("1", "A"))
.addInsertion("row2", columnFamilyDefinition.getName(), HFactory.createStringColumn("2", "B"))
.addInsertion("row2", columnFamilyDefinition.getName(), HFactory.createStringColumn("3", "C"));
mutator.execute();
}
// RangeSliceQuery
public void read1() {
if (null == cluster || null == keySpace) {
// throw exception
return;
}
int row_count = 100;
RangeSlicesQuery<String, String, String> rangeSlicesQuery = HFactory
.createRangeSlicesQuery(keySpace, StringSerializer.get(), StringSerializer.get(), StringSerializer.get())
.setColumnFamily(COLUMN_FAMILY_NAME)
.setRange(null, null, false, 10)
.setRowCount(row_count);
String last_key = null;
while (true) {
rangeSlicesQuery.setKeys(last_key, null);
QueryResult<OrderedRows<String, String, String>> result1 = rangeSlicesQuery.execute();
System.out.println( result1);
OrderedRows<String, String, String> rows1 = result1.get();
Iterator<Row<String, String, String>> rowsIterator = rows1.iterator();
// we'll skip this first one, since it is the same as the last one from previous time we executed
if (last_key != null && rowsIterator != null) {
rowsIterator.next();
}
while (rowsIterator.hasNext()) {
Row<String, String, String> row = rowsIterator.next();
last_key = row.getKey();
if (row.getColumnSlice().getColumns().isEmpty()) {
continue;
}
System.out.println(row);
ColumnSlice<String, String> columnSlice = row.getColumnSlice();
Iterator<HColumn<String, String>> columnSliceIterator = columnSlice.getColumns().listIterator();
while (columnSliceIterator.hasNext()) {
HColumn<String, String> hColumn = columnSliceIterator.next();
System.out.println(" name : " + hColumn.getName() + ", value : " + hColumn.getValue());
}
}
if (rows1.getCount() < row_count) {
break;
}
}
}
// Cqlquery
public void read2() {
if (null == cluster || null == keySpace) {
// throw exception
return;
}
// CqlQuery
CqlQuery<String, String, String> cqlQuery = new CqlQuery<String, String, String>(
keySpace, StringSerializer.get(), StringSerializer.get(),
StringSerializer.get());
cqlQuery.setQuery("select * from " + COLUMN_FAMILY_NAME);
QueryResult<CqlRows<String, String, String>> result = cqlQuery.execute();
CqlRows<String, String, String> rows = result.get();
if (null != rows) {
System.out.println();
for (int i = 0; i < rows.getCount(); i++) {
RowImpl<String, String, String> row = (RowImpl<String, String, String>) rows.getList().get(i);
System.out.println("Row key = " + row.getKey());
for (HColumn<String, String> column : row.getColumnSlice().getColumns()) {
System.out.println(" Column name = " + column.getName().toString() + ", value = " + column.getValue().toString());
}
}
}
}
}
4. Astyanax
pom.xml
<dependency>
<groupId>com.netflix.astyanax</groupId>
<artifactId>astyanax-cassandra</artifactId>
<version>1.56.37</version>
</dependency>
<dependency>
<groupId>com.netflix.astyanax</groupId>
<artifactId>astyanax-thrift</artifactId>
<version>1.56.37</version>
</dependency>
code
package com.google.cassandra.client;
import com.netflix.astyanax.AstyanaxContext;
import com.netflix.astyanax.ColumnListMutation;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.connectionpool.NodeDiscoveryType;
import com.netflix.astyanax.connectionpool.OperationResult;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolConfigurationImpl;
import com.netflix.astyanax.connectionpool.impl.CountingConnectionPoolMonitor;
import com.netflix.astyanax.impl.AstyanaxConfigurationImpl;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.model.ColumnList;
import com.netflix.astyanax.model.CqlResult;
import com.netflix.astyanax.model.Row;
import com.netflix.astyanax.serializers.StringSerializer;
import com.netflix.astyanax.thrift.ThriftFamilyFactory;
public class AstyanaxTest {
public static void main(String[] args) {
AstyanaxTest sample = new AstyanaxTest();
sample.getConfig();
sample.create();
sample.insert();
sample.list();
}
/*
cqlsh:userkeyspace> describe columnfamily cf21
CREATE TABLE cf21 (
key text,
number text,
name text,
PRIMARY KEY (key, number)
) WITH COMPACT STORAGE AND
bloom_filter_fp_chance=0.010000 AND
caching='KEYS_ONLY' AND
comment='' AND
dclocal_read_repair_chance=0.000000 AND
gc_grace_seconds=864000 AND
index_interval=128 AND
read_repair_chance=0.100000 AND
replicate_on_write='true' AND
populate_io_cache_on_flush='false' AND
default_time_to_live=0 AND
speculative_retry='NONE' AND
memtable_flush_period_in_ms=0 AND
compaction={'class': 'SizeTieredCompactionStrategy'} AND
compression={'sstable_compression': 'LZ4Compressor'};
cqlsh:userkeyspace> select * from cf21;
key | number | name
------+--------+------
row1 | 1 | Kim
row1 | 2 | Yun
row1 | 3 | Park
row2 | 1 | Choi
*/
public static final String CLUSTER_NAME = "Test Cluster";
public static final String KEY_SPACE_NAME = "userkeyspace";
public static final String COLUMN_FAMILY_NAME = "cf21";
private AstyanaxContext<Keyspace> context;
private Keyspace keyspace;
private ColumnFamily<String, String> COLUMN_FAMILY;
public void getConfig() {
context = new AstyanaxContext.Builder()
.forCluster(CLUSTER_NAME)
.forKeyspace(KEY_SPACE_NAME)
.withAstyanaxConfiguration(new AstyanaxConfigurationImpl()
.setDiscoveryType(NodeDiscoveryType.RING_DESCRIBE))
// connection pool support
.withConnectionPoolConfiguration(new ConnectionPoolConfigurationImpl("MyConnectionPool")
.setPort(9160).setMaxConnsPerHost(1)
.setSeeds("127.0.0.1:9160"))
.withAstyanaxConfiguration(new AstyanaxConfigurationImpl().setCqlVersion("3.0.0")
.setTargetCassandraVersion("2.0.1"))
.withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
.buildKeyspace(ThriftFamilyFactory.getInstance());
context.start();
keyspace = context.getClient();
COLUMN_FAMILY = ColumnFamily.newColumnFamily(COLUMN_FAMILY_NAME,
StringSerializer.get(), StringSerializer.get());
}
public void insert() {
try {
String statement = String.format("insert into " + COLUMN_FAMILY_NAME + " (key, number, name) values (?, ?, ?) \n");
keyspace.prepareQuery(COLUMN_FAMILY)
.withCql(statement)
.asPreparedStatement()
.withStringValue("row1")
.withStringValue("1")
.withStringValue("Kim")
.execute();
keyspace.prepareQuery(COLUMN_FAMILY)
.withCql(statement)
.asPreparedStatement()
.withStringValue("row1")
.withStringValue("2")
.withStringValue("Yun")
.execute();
keyspace.prepareQuery(COLUMN_FAMILY)
.withCql(statement)
.asPreparedStatement()
.withStringValue("row1")
.withStringValue("3")
.withStringValue("Park")
.execute();
keyspace.prepareQuery(COLUMN_FAMILY)
.withCql(statement)
.asPreparedStatement()
.withStringValue("row2")
.withStringValue("1")
.withStringValue("Choi")
.execute();
} catch (ConnectionException e) {
throw new RuntimeException("failed to write data to cql", e);
}
}
public void insertBatch(String key, String[]... entries) {
MutationBatch m = keyspace.prepareMutationBatch();
ColumnListMutation<String> clm = m.withRow(COLUMN_FAMILY, key);
for (String[] kv : entries) {
clm.putColumn(kv[0], kv[1], null);
}
try {
m.execute();
} catch (ConnectionException e) {
throw new RuntimeException("failed to write data to batch insert", e);
}
}
public void create() {
drop();
String statement = "create table IF NOT EXISTS " + COLUMN_FAMILY_NAME
+ " (KEY text, number text, name text, PRIMARY KEY (KEY, number)) WITH COMPACT STORAGE;";
try {
keyspace.prepareQuery(COLUMN_FAMILY)
.withCql(statement)
.execute();
} catch (ConnectionException e) {
throw new RuntimeException("failed to create table", e);
}
}
public void list() {
String statement = "SELECT * FROM " + COLUMN_FAMILY_NAME + " WHERE key = ?";
try {
OperationResult<CqlResult<String, String>> result = keyspace.prepareQuery(COLUMN_FAMILY)
.withCql(statement)
.asPreparedStatement()
.withStringValue("row1")
.execute();
for (Row<String, String> row : result.getResult().getRows()) {
ColumnList<String> cols = row.getColumns();
System.out.println("- key : " + cols.getStringValue("key", null) + ", name : " +
cols.getStringValue("name", null) + ", number : " +
cols.getStringValue("number", null));
}
} catch (ConnectionException e) {
throw new RuntimeException("failed to read from cql", e);
}
}
public void drop() {
try {
keyspace.prepareQuery(COLUMN_FAMILY)
.withCql("drop table IF EXISTS " + COLUMN_FAMILY_NAME)
.execute();
} catch (ConnectionException e) {
throw new RuntimeException("failed to create table", e);
}
}
}
5. Easy Cassandra
Easycassandra는 JPA 규격을 따르는 Kundera와 비슷하다. Kunder도 아래와 같이 비슷하게 테스트할 수 있다.
pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons-core</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.easycassandra</groupId>
<artifactId>EasyCassandra</artifactId>
<version>2.0.0-RC3</version>
</dependency>
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>1.0.3</version>
</dependency>
code
package com.google.cassandra.client;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.google.cassandra.client.spring.Person;
import com.google.cassandra.client.spring.PersonRepository;
public class EasyCassandraTest {
/*
CREATE TABLE cf33 (
key text,
number text,
name text,
PRIMARY KEY (key, number)
)
*/
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
PersonRepository personService = ctx.getBean(PersonRepository.class);
Person person = new Person();
person.setKey("row1");
person.setName("Kim");
person.setNumber("1");
personService.save(person);
person = new Person();
person.setKey("row1");
person.setName("John");
person.setNumber("2");
personService.save(person);
Iterable<Person> iter = personService.findAll();
for (Person p : iter) {
System.out.println("key : " + p.getKey() + ", number : " + p.getNumber() + " , name : " + p.getName());
}
Person xman = personService.findOne("row1");
System.out.println("xman : " +xman.getName());
}
}
package com.google.cassandra.client.spring;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.easycassandra.Index;
// easy
@Entity(name = "cf33")
public class Person implements Serializable {
private static final long serialVersionUID = 3L;
@Id
private String key;
@Index
@Column(name = "name")
private String name;
@Column(name = "number")
private String number;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setNumber(String number) {
this.number = number;
}
public String getNumber() {
return number;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
return true;
}
}
package com.google.cassandra.client.spring;
import org.easycassandra.persistence.cassandra.spring.CassandraRepository;
import org.easycassandra.persistence.cassandra.spring.CassandraTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository("personRepository")
public class PersonRepository extends CassandraRepository<Person, String> {
@Autowired
private CassandraTemplate cassandraTemplate;
@Override
protected CassandraTemplate getCassandraTemplate() {
return cassandraTemplate;
}
}
'nosql' 카테고리의 다른 글
cassandra - rapid read protection (0) | 2013.11.05 |
---|---|
cassandra version upgrade(update) (0) | 2013.11.05 |
cassandra java client api 선택 & 비교 (0) | 2013.11.04 |
cassandra bench mark 자료 모음 (0) | 2013.10.31 |
cassandra 2.0/java driver - consistencylevel 지정하기 (0) | 2013.10.30 |