요즘 데이터의 풍요속에서 데이터를 처리하기 위해서 필요한 데이터 전송 포맷이 매우 다양하죠..
따라서, 데이터를 네트웍으로 전송하기 위한 포맷을 선택하는 것이 시스템 전체적인 성능이나 유연성을 좌우하기에 매우 중요한 팩트가 되었습니다..

그래서, 데이터 포맷별로 테스트한 자료와 성능에 대한 검색자료를 정리해 봅니다.. ^^

1. Java Serialize Benchmarking

- 이 테스트 자료는 자바환경에서 https://github.com/eishay/jvm-serializers 프로젝트에서 테스트한 자료입니다.
- 테스트 결과중에 속도에 대한 차트만 첨부했습니다. 예전의 테스트 자료에서는 kryo가 protobuf보다 더 빠른 결과가 나왔었는데, 2011-07-13일 버전의 테스트 자료에서는 역전을 했네요.. ^^ 그리고, 위의 테스트 결과 위키에서의 답글(2011-10-27)을 보면, 테스트 결과에서는 kyro가 상당히 의미있는 결과를 보여주고 있네요.. 그리고 테스트 결과를 바탕으로 json 포맷을 지원하는 라이브러리 선택도 의미가 있을 것 같습니다.
- 이 테스트 자료는 상당히 방대한 자료에 대한 테스트를 진행했기 때문에 정말 유익합니다.. 꼭 자세히 살펴볼 필요가 있습니다.. 하지만, 최근(?)에 사용을 늘려가고 있는 MessagePack과 YAML에 대한 자료가 없는건 아쉽네요..


- 테스트한 결과에 대한 스냅샷을 위해서 .mht 파일로 첨부했습니다..
 



2. MessagePack에 대해서 고려한 카산드라..

- 카산드라 0.7버전에서 MessagePack을 thrift의 대안으로 고려를 했었습니다.. 물론 카산드라 버전에서 MessagePack 라이브러리를 살펴볼 수 없기 때문에 채택이 안되었겠죠.. ^^ 카산드라의 JIRA CASSANDRA-1735에서 카산드라 프로젝트의 의장인 Jonathan Ellis의 코멘트를 보면, 의미가 없었다고 하네요..
Gary did some tests in CASSANDRA-1765 and found no significant advantage over Thrift. Given that, and our brief experience supporting a second rpc protocol (Avro in the 0.7 series), I don't think this is going anywhere.

- JIRA에서 살펴보면, 테스트 결과는 꽤 성능향상 이점(random read 15%, random write 21%)이 있어 보이긴 하네요.. 흠.. 위의 Jonathan Ellis의 코멘트가 사실이라면, 역시 테스트는 데이타에 따라 결과에 대한 차이가 상당한 것 같습니다..

Performance improvement available with this patch will be the following:

  • Reducing serialization cost and the data size
  • Increase throughput between clients and a Cassandra node

I have also measured the performance of MessagePack, from the viewpoints of reducing serialization cost and throughput. I will discuss details below.

== Reduction of serialization cost and the data size ==

(Summary)
MessagePack has proved to be better in reducing serialzation cost and the data size compared to other serialization libraries in the test below.

(Test environment)
I used "jvm-serializers" which is a well-known benchmark and compared performances with Protocol Buffers, Thrift, and Avro. Machine used for this benchmark has Core2 Duo 2GHz with 1GB RAM.

(Results)
      create  ser +same deser +shal +deep total size +dfl
protobuf    683 6016 2973  3338  3454 3759 9775 239 149
thrift      572 6287 5565  3479  3616 3770 10057 349 197
msgpack    291 4935 4750  3468  3545 3708 8748 236 150
avro     2698 6409 3623  7480  9301 10481 16890 221 133

(Comments)
It may be better to compare serialization cost using objects with Cassandra like a Column object. But such objects and sizes vary by users, and is not suitable for comparing serialization cost of various data. According to the above result, the size of MessagePack's serialized data is slightly larger than Avro. But MessagePack has significantly low serialization cost compared to Avro and Thrift.

== Increasing throughput ==

(Summary)
I compared MessagePack based RPC of Cassandra to that of Thrift. Random read throughput of MessagePack based RPC is 15% higher than that of Thrift and random write throughput is 21% higher.

(Test environment)
In this evaluation, Cassandra node ran as a standalone on a machine with Core2 Duo 2GHz and 1GB RAM. Client programs ran on two machines both with Core2 Duo 2GHz and 1GB RAM. Client program was based on ring cache. It created 100 threads per a JVM on each machine and accesses to a Cassandra node with ring cache.

(Results)

  • Thrift based RPC part of Cassandra(read: 5,200 query/sec., write: 11,200 query/sec.)
  • MessagePack based RPC part of Cassandra (read: 6,000 query/sec., write: 13,600 query/sec.)

(Comments)
I measured the max throughput of random access (read/write) after 100 items (size of each item is small) were stored in the Cassandra node. The reason is because I wanted to make the state of CPU bottle neck for the Cassandra node. If the Cassandra node is the state of Disk IO bottle neck, I thought that I cannot properly evaluate max throughput of the RPC part.

I did not measure the amount of data transferred in network during the evaluation directly. But from the benchmark result of jvm-serializers, I believe that the amount of transferred data for MessagePack-based Cassandra would be reduced compared to that of Thrift.


3. Serializing data speed comparison: Marshal vs. JSON vs. Eval vs. YAML

- 이 테스트 자료는 루비로 테스트를 했다고 하네요..
 

Last night at the NYC Ruby hackfest, I got into a discussion about serializing data. Brian mentioned the Marshal library to me, which for some reason had completely escaped my attention until last night. He said it was wicked fast so we decided to run a quick benchmark comparison.

The test data is designed to roughly approximate what my stored classifier data will look like. The different methods we decided to benchmark were Marshal, json, eval, and yaml. With each one we took the in-memory object and serialized it and then read it back in. With eval we had to convert the object to ruby code to serialize it then run eval against that. Here are the results for 100 iterations on a 10k element array and a hash with 10k key/value pairs run on my Macbook Pro 2.4 GHz Core 2 Duo:

                 user      system     total       realarray marshal  0.210000   0.010000   0.220000 (  0.220701)array json     2.180000   0.050000   2.230000 (  2.288489)array eval     2.090000   0.060000   2.150000 (  2.240443)array yaml    26.650000   0.350000  27.000000 ( 27.810609)
hash marshal   2.000000   0.050000   2.050000 (  2.114950)hash json      3.700000   0.060000   3.760000 (  3.881716)hash eval      5.370000   0.140000   5.510000 (  6.117947)hash yaml     68.220000   0.870000  69.090000 ( 72.370784)

The order in which I tested them is pretty much the order in which they ranked for speed. Marshal was amazingly fast. JSON and eval came out roughly equal on the array with eval trailing quite a bit for the hash. Yaml was just slow as all hell. A note on the json: I used the 1.1.3 library which uses c to parse. I assume it would be quite a bit slower if I used the pure ruby implementation. Here's a gist of the benchmark code if you're curious and want to run it yourself.

If you're serializing user data, be super careful about using eval. It's probably best to avoid it completely. Finally, just for fun I took yaml out (it was too slow) and ran the benchmark again with 1k iterations:

                 user      system     total       realarray marshal  2.080000   0.110000   2.190000 (  2.242235)array json    21.860000   0.500000  22.360000 ( 23.052403)array eval    20.730000   0.570000  21.300000 ( 21.992454)
hash marshal  19.510000   0.500000  20.010000 ( 20.794111)hash json     39.770000   0.670000  40.440000 ( 41.689297)hash eval     51.410000   1.290000  52.700000 ( 54.155711)

시스템을 설계하면서 네트웍으로 데이터를 전송/수신하기 위한 포맷은 위의 자료로 대부분 살펴본 것 같습니다.
개발하는 시스템의 성격에 따라서 속도와 사이즈 어떤 것이 중요할지는 개발자의 판단이고..
이 자료가 매우 도움이 되었으면 좋겠습니다.. ^^

저작자 표시
카산드라는 0.7 버전부터인가?? YAML 포맷의 파일을 설정파일로 사용하기 시작을 했다..
기존에는 YAML 파일은 JSON 포맷과 다른 또 다른 포맷으로만 알고 있었는데, 위키의 YAML 포맷에 대한 정의를 살펴보면, 사람이 쉽게 읽을 수 있는 데이터 직렬화 양식이라고 한다.. 흠 그래.. 쪼매 쉽게 읽히긴 한다..
아래에서 0.6 버전에서 사용했던 XML 포맷과 현재(1.0.2)에서 사용하고 있는 YAML 포맷을 살펴보자.. 어떤 설정이 더 가독성이 있을까? 라는 질문에 나는 XML 포맷이라고 답하겠다..

단순히 포맷만 보면, XML이 YAML 포맷에 비해서 비 효율적이고 파싱에 대한 비용도 많이 들겠다.. 하지만, 카산드라에서 아래의 용도는 클러스터/머신의 상황에 맞게 카산드라가 잘 돌게 하기 위한 설정이다.. 설정이라고 하면, 포맷에 맞춰서 설정한 값의 가독성이 매우 중요한 포인트라고 생각한다.  그런 면에서 나는 꼭 설정에 XML을 사용할 필요는 없겠지만, 가급적이면 YAML보다 쉽고(비교적 쉽게 느껴지는 주관) 가독성이 좋은 XML을 사용해 줬으면 하지만, 지금은 YAML 포맷이니.. YAML 포맷을 숙지하고 사용해야 겠지만, 아쉬운 느낌이다.. 아.. XML 포맷이 좋아지다니... ㅋㅋㅋ

<Storage>
  <ClusterName>Test Cluster</ClusterName>
  <AutoBootstrap>false</AutoBootstrap>
  <Keyspaces>
    <Keyspace Name="Keyspace1">
      <ColumnFamily CompareWith="BytesType"
                    Name="Standard1"
                    RowsCached="10%"
                    KeysCachedFraction="0"/>
      <ColumnFamily CompareWith="UTF8Type" Name="Standard2"/>
      <ColumnFamily CompareWith="TimeUUIDType" Name="StandardByUUID1"/>
      <ColumnFamily ColumnType="Super"
                    CompareWith="UTF8Type"
                    CompareSubcolumnsWith="UTF8Type"
                    Name="Super1"
                    RowsCached="1000"
                    KeysCachedFraction="0"
                    Comment="A column family with supercolumns, whose column and subcolumn names are UTF8 strings"/>
      <ReplicaPlacementStrategy>org.apache.cassandra.locator.RackUnawareStrategy</ReplicaPlacementStrategy>
      <ReplicationFactor>1</ReplicationFactor>
      <EndPointSnitch>org.apache.cassandra.locator.EndPointSnitch</EndPointSnitch>    
    </Keyspace>
  </Keyspaces>

  <Authenticator>org.apache.cassandra.auth.AllowAllAuthenticator</Authenticator>
  <Partitioner>org.apache.cassandra.dht.RandomPartitioner</Partitioner>
  <InitialToken></InitialToken>

  <CommitLogDirectory>/var/lib/cassandra/commitlog</CommitLogDirectory>
  <DataFileDirectories>
      <DataFileDirectory>/var/lib/cassandra/data</DataFileDirectory>
  </DataFileDirectories>
  <CalloutLocation>/var/lib/cassandra/callouts</CalloutLocation>
  <StagingFileDirectory>/var/lib/cassandra/staging</StagingFileDirectory>

  <Seeds>
      <Seed>127.0.0.1</Seed>
  </Seeds>

  <RpcTimeoutInMillis>5000</RpcTimeoutInMillis>
  <CommitLogRotationThresholdInMB>128</CommitLogRotationThresholdInMB>
  <ListenAddress>localhost</ListenAddress>
  <StoragePort>7000</StoragePort>
  <ThriftAddress>localhost</ThriftAddress>
  <ThriftPort>9160</ThriftPort>
  <ThriftFramedTransport>false</ThriftFramedTransport>


  <DiskAccessMode>auto</DiskAccessMode>
  <SlicedBufferSizeInKB>64</SlicedBufferSizeInKB>
  <FlushDataBufferSizeInMB>32</FlushDataBufferSizeInMB>
  <FlushIndexBufferSizeInMB>8</FlushIndexBufferSizeInMB>
  <ColumnIndexSizeInKB>64</ColumnIndexSizeInKB>
  <MemtableThroughputInMB>64</MemtableThroughputInMB>
  <BinaryMemtableThroughputInMB>256</BinaryMemtableThroughputInMB>
  <MemtableOperationsInMillions>0.3</MemtableOperationsInMillions>
  <MemtableFlushAfterMinutes>60</MemtableFlushAfterMinutes>
  <ConcurrentReads>8</ConcurrentReads>
  <ConcurrentWrites>32</ConcurrentWrites>
  <CommitLogSync>periodic</CommitLogSync>
  <CommitLogSyncPeriodInMS>10000</CommitLogSyncPeriodInMS>
  <GCGraceSeconds>864000</GCGraceSeconds>
</Storage>

cluster_name: 'Test Cluster'
initial_token:
hinted_handoff_enabled: true
max_hint_window_in_ms: 3600000 # one hour
hinted_handoff_throttle_delay_in_ms: 50
authenticator: org.apache.cassandra.auth.AllowAllAuthenticator
authority: org.apache.cassandra.auth.AllowAllAuthority
partitioner: org.apache.cassandra.dht.RandomPartitioner
data_file_directories:
    - /var/lib/cassandra/data
commitlog_directory: /var/lib/cassandra/commitlog
saved_caches_directory: /var/lib/cassandra/saved_caches
commitlog_sync: periodic
commitlog_sync_period_in_ms: 10000

seed_provider:
    - class_name: org.apache.cassandra.locator.SimpleSeedProvider
      parameters:
          - seeds: "127.0.0.1"

flush_largest_memtables_at: 0.75
reduce_cache_sizes_at: 0.85
reduce_cache_capacity_to: 0.6
concurrent_reads: 32
concurrent_writes: 32
memtable_flush_queue_size: 4
sliced_buffer_size_in_kb: 64
storage_port: 7000
ssl_storage_port: 7001
listen_address: localhost
rpc_address: localhost
rpc_port: 9160
rpc_keepalive: true

rpc_server_type: sync
thrift_framed_transport_size_in_mb: 15
thrift_max_message_length_in_mb: 16
incremental_backups: false
snapshot_before_compaction: false
column_index_size_in_kb: 64
in_memory_compaction_limit_in_mb: 64
multithreaded_compaction: false
compaction_throughput_mb_per_sec: 16
compaction_preheat_key_cache: true
rpc_timeout_in_ms: 10000
endpoint_snitch: org.apache.cassandra.locator.SimpleSnitch
dynamic_snitch_update_interval_in_ms: 100
dynamic_snitch_reset_interval_in_ms: 600000
dynamic_snitch_badness_threshold: 0.1
request_scheduler: org.apache.cassandra.scheduler.NoScheduler
index_interval: 128

encryption_options:
    internode_encryption: none
    keystore: conf/.keystore
    keystore_password: cassandra
    truststore: conf/.truststore
    truststore_password: cassandra


저작자 표시
아래 내용은 http://www.datastax.com/faq#intro-3 에 있는 내용입니다..
설명이 간단 명료해서 쉽게 차이점을 캐치하실 수 있습니다.. ^^
How does Cassandra differ from Hadoop?

The primary difference between Cassandra and Hadoop is that Cassandra targets real-time/operational data, while Hadoop has been designed for batch-based analytic work.

There are many different technical differences between Cassandra and Hadoop, including Cassandra’s underlying data structure (based on Google’s Bigtable), its fault-tolerant, peer-to-peer architecture, multi-data center capabilities, tunable data consistency, all nodes being the same (no concept of a namenode, etc.) and much more.

How does Cassandra differ from HBase?

HBase is an open-source, column-oriented data store modeled after Google Bigtable, and is designed to offer Bigtable-like capabilities on top of data stored in Hadoop. However, while HBase shared the Bigtable design with Cassandra, its foundational architecture is much different.

A Cassandra cluster is much easier to setup and configure than a comparable HBase cluster. HBase’s reliance on the Hadoop namenode equates to there being a single point of failure in HBase, whereas with Cassandra, because all nodes are the same, there is no such issue.

In internal performance tests conducted at DataStax (using the Yahoo Cloud Serving Benchmark – YCSB), Cassandra offered literally 5X better performance in writes and 4X better performance on reads than HBase.

How does Cassandra differ from MongoDB?

MongoDB is a document-oriented database that is built upon a master-slave/sharding architecture. MongoDB is designed to store/manage collections of JSON-styled documents.

By contrast, Cassandra uses a peer-to-peer, write/read-anywhere styled architecture that is based on a combination of Google BigTable and Amazon Dynamo. This allows Cassandra to avoid the various complications and pitfalls of master/slave and sharding architectures. Moreover, Cassandra offers linear performance increases as new nodes are added to a cluster, scales to terabyte-petabyte data volumes, and has no single point of failure.


저작자 표시
카산드라(Cassandra)를 사용하거나 혹은 사용하기를 고려하는 분이라면 읽어보면 좋을 2개의 파일이 있는데, 아래의 파일들은 카산드라의 압축을 풀면 최상단에 위치하는 파일들입니다.

한개는 README.txt 이고, 다른 한개는 NEWS.txt 입니다..  
README.txt는 카산드라에 대한 개략적인 내용과 설치에 대한 내용이 들어 있습니다..
NEWS.txt는 카산드라가 버전업이 되면서, 바뀌는 내용을 개략적으로 기술한 파일입니다..


그리고, 좀 더 자세히 살펴보실 분들은 NOTICE.txtCHANGES.txt 을 검토해 보길 권해 드립니다..
NOTICE.txt 파일에는 카산드라가 사용하고 있는 Dependency Library에 대한 내용을 포함하고 있습니다..
CHANGES.txt 파일에는 카산드라 버전이 업데이트 되면서, 새롭게 추가되거나 수정된 내용을 이슈트래킹 번호를 포함해서 보여주고 있습니다.. 따라서 자세한 내용은 CHANGES.txt 파일의 이슈트래킹 번호를 따라 들어가게 되면, 버전 업에 따른 좀 더 세부적인 내용을 살펴볼 수 있습니다.. 


이상, 카산드라를 무작정 사용하는 것도 좋겠지만, 한번 읽어보면 좋을 만한 카산드라 파일에 대한 내용이었습니다.. ^^ 
저작자 표시
아.. 
오랜만에 cassandra-cli로 키스페이스 맹글고, 컬럼에 데이터 넣고.. 하는데...
위에처럼, 컬럼 이름(xxx)을 파싱할 수 없다고 하네요.. ^^;; 헉..^^;;

모지... 모지.. 찾아보니.. 
아래 요기 링크들을 들어가 보세요.. ^^

요기, 요기를 살펴보세요.. ^^
주욱주욱 훑어보니.. key_validation_class=UTF8Type <-- 이거 추가해줘야 하네요.. ^^;;
 

흠.. 카산드라는 너무 다이나믹하게 업뎃이 되네요.. ^^;;

결론.. 아래처럼 validation class로 utf8type을 줘서 컬럼 패밀리를 생성한다 네요. ^^

create column family Users with comparator=UTF8Type
and default_validation_class=UTF8Type and key_validation_class=UTF8Type; 


저작자 표시

Cassandra.Client는 org.apache.cassandra.thrift 패키지의 클래스이고, 결국, Client는 Cassandra의 Inner 클래스가 됩니다..그리고, 위 패키지는 Thrift라는 데이타 serialize/deserialize 라이브러리(Google Protocol Buffers랑 비슷)를 통해서 전송될 데이타를 만들고, 전송된 데이타를 처리하고 있겠죵.. Cassandra의 언어별 클라이언트 라이브러리는 http://wiki.apache.org/cassandra/ClientOptions 페이지에 자세히 기술이 되어 있습니다.. 클라이언트 라이브러리들은 보통 Cassandra 서버에 붙는 Connection에 대한 풀링을 제공하는데, Connection 풀링은 org.apache.cassandra.thrift 패키지의 Cassandra.Client를 풀링해서 구현 할 수 있습니다. 
아래 코드는 Cassandra.Client의 풀링을 통한 Cassandra 서버의 연결에 대한 풀링기능을 제공하고 있습니다..^^

* CassandraClientArrayFactory.java

package net.sjava.cassandra.test;

import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.cassandra.thrift.Cassandra;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

/**
 * Cassandra.Client 풀링 클래스
 *
 * @author mcsong@gmail.com
 * @since 2010/11/30
 *
 */
public class CassandraClientArrayFactory {
 /**
  * host array
  */
 private static String[] hosts = "127.0.0.1,127.0.0.1".split(",") ;
 /**
  * port
  */
 private static int port = 9160;
 /**
  * pooing count
  */
 private static int count = 10;
 
 //
 private static ConcurrentLinkedQueue<Cassandra.Client> clients = new  ConcurrentLinkedQueue<Cassandra.Client>();
 
 /**
  * Cassandra.Client를 생성한다.
  * @return
  * @throws Exception
  */
 private static Cassandra.Client createCassandraClient() throws Exception {
  int index = new Random().nextInt(hosts.length);
  TTransport socket = new TSocket(hosts[index], port);
  socket.open();
  return new Cassandra.Client(new TBinaryProtocol(socket, false, false));
 }

 /**
  * Cassandra.Client를 풀에서 가져온다.
  * @return
  * @throws Exception
  */
 public static Cassandra.Client poll() throws Exception {
  if (!clients.isEmpty() && clients.peek() != null)
   return clients.poll();
  
  return createCassandraClient();
 }
 
 /**
  * Cassandra.Client를 풀에 넣는다.
  * @param client
  * @throws Exception
  */
 public static void push(Cassandra.Client client) throws Exception {
  System.out.println("channel size : " + clients.size());
  if (clients.size() >= count) {
   client = null; // garbage
   return;
  }
  
  clients.offer(client);
 }
}



* CassandraClientArrayFactoryTest.java 

package net.sjava.cassandra.test;

import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnPath;
import org.apache.cassandra.thrift.ConsistencyLevel;

import static net.sjava.cassandra.test.CassandraClientArrayFactory.poll;
import static net.sjava.cassandra.test.CassandraClientArrayFactory.push;

public class CassandraClientArrayFactoryTest {

 public static void main(String[] args) {
  
  String keyspace = "Keyspace1";
  String columnFamily = "Standard2";
  String key = "key1";
  long timestamp = System.currentTimeMillis();
  
  Cassandra.Client client = null;
  
  try {
   client = poll();   
   for(int i=0; i < 15; i++)
    push(client);
     
   String value ="bbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
   ColumnPath cPath = new ColumnPath(columnFamily);
   cPath.setColumn("name".getBytes("utf-8"));
   client.insert(keyspace, key, cPath, value.getBytes("utf-8"), timestamp, ConsistencyLevel.ONE);
   Column col = client.get(keyspace, key, cPath, ConsistencyLevel.ONE).getColumn();
   System.out.println("Column name: " + new String(col.name, "utf-8")); 
   System.out.println("Column value: " + new String(col.value, "utf-8")); 
  
   value ="ccccccccccccccccccccccccccccccccccccccc";
   long time2 = System.currentTimeMillis();
   client.insert(keyspace, key, cPath, value.getBytes("utf-8"), time2, ConsistencyLevel.ONE);
   Column col2 = client.get(keyspace, key, cPath, ConsistencyLevel.ONE).getColumn();
   System.out.println("Column2 name: " + new String(col2.name, "utf-8")); 
   System.out.println("Column2 value: " + new String(col2.value, "utf-8")); 
  } catch(Exception e) {
   e.printStackTrace();
  } finally {
   if(client != null)
    try {
     push(client);
    } catch (Exception e) {
     e.printStackTrace();
    }
  }
 }

}


저작자 표시
Client 객체는 기본적으로, Cassandra.Client 생성을 클래스 예제 코드를 같이 사용하고 있습니다.
가장 기초적인 1개의 Column에 데이타 insert/get 하는 예제입니다..

package net.sjava.cassandra.test;

import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnPath;
import org.apache.cassandra.thrift.ConsistencyLevel;

public class CassandraTest {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        CassandraClientFactory factory = CassandraClientFactory.getInstance();
        String keyspace = "Keyspace1";
        String columnFamily = "Standard2";
        String key = "key1";
        long timestamp = System.currentTimeMillis();
       
        String value ="aaaaaaaaaaaaaaaaaaa_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
        try {
            ColumnPath cPath = new ColumnPath(columnFamily);
            cPath.setColumn("name".getBytes("utf-8"));
            factory.getClient().insert(keyspace, key, cPath, value.getBytes("utf-8"), timestamp, ConsistencyLevel.ONE);
            Column col = factory.getClient().get(keyspace, key, cPath, ConsistencyLevel.ONE).getColumn();
            System.out.println("Column name: " + new String(col.name, "utf-8")); 
            System.out.println("Column value: " + new String(col.value, "utf-8")); 
       
            value ="aaaaaaaaaa";
           
            long time2 = System.currentTimeMillis();
            factory.getClient().insert(keyspace, key, cPath, value.getBytes("utf-8"), time2, ConsistencyLevel.ONE);
            Column col2 = factory.getClient().get(keyspace, key, cPath, ConsistencyLevel.ONE).getColumn();
            System.out.println("Column2 name: " + new String(col2.name, "utf-8")); 
            System.out.println("Column2 value: " + new String(col2.value, "utf-8")); 
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}


저작자 표시
Cassandra에 대한 좋은 설명과 예제들..

1. Getting Started With Cassandra <-- 강추..

2. http://nosql.mypopescu.com/tagged/cassandra

3. http://blog.evanweaver.com/articles/2009/07/06/up-and-running-with-cassandra/

4. http://www.sodeso.nl/?cat=10 <-- 여기도 강추..
4.1 Installing and using Apache Cassandra With Java Part 1 (Installation)
4.2 Installing and using Apache Cassandra With Java Part 2 (Data model)
4.3 Installing and using Apache Cassandra With Java Part 3 (Data model 2)
4.4 Installing and using Apache Cassandra With Java Part 4 (Thrift Client)
4.5 Installing and using Apache Cassandra With Java Part 5 (Thrift Client 2)
저작자 표시

'Apache Project > Cassandra' 카테고리의 다른 글

Cassandra.Client 풀링하기..  (2) 2010/12/01
Cassandra simple insert/get 하기..  (2) 2010/11/28
Cassandra에 대한 좋은 설명과 예제들..  (0) 2010/10/14
Cassandra 발표 자료  (0) 2010/07/06
ConsistencyLevel에 대해서..  (0) 2010/07/02
Tag // Cassandra
보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.
카산드라에 대한 내용 정리 자료입니다...
Introduction 수준이며, 테스트 자료는 명확하지 않을 수 있습니다.
대략적인 내용은 아래와 같습니다.
1.Definition
2.History & Reference
3.Features
4.Data Model
5.Project Package
6.Performance
7.적용가능 부분
8.Q&A


저작자 표시
Cassandra의 경우, Cassandra의 서버 설정에서 <ReplicationFactor>1</ReplicationFactor>를 통해서 데이타 복제에 대한 설정을 할 수 잇습니다. 클라이언트에서는 데이타를 쓰고, 읽는데 ConsistencyLevel을 통해서 Async 또는 Sync(1개만 되면 리턴, 설정된 개수만큼 저장이 되야 리턴)등의 설정 파라미터를 통해서 정책적으로 성격에 맞게 사용할 수 있습니다. 그래서, ConsistencyLevel은 잘 알고 있어야 할거 같습니다.
0.6.2버전에서의 ConsitencyLevel에 대한 주석내용은 아래와 같습니다.
/**
 * The ConsistencyLevel is an enum that controls both read and write behavior based on <ReplicationFactor> in your
 * storage-conf.xml. The different consistency levels have different meanings, depending on if you're doing a write or read
 * operation. Note that if W + R > ReplicationFactor, where W is the number of nodes to block for on write, and R
 * the number to block for on reads, you will have strongly consistent behavior; that is, readers will always see the most
 * recent write. Of these, the most interesting is to do QUORUM reads and writes, which gives you consistency while still
 * allowing availability in the face of node failures up to half of <ReplicationFactor>. Of course if latency is more
 * important than consistency then you can use lower values for either or both.
 *
 * Write:
 *      ZERO    Ensure nothing. A write happens asynchronously in background
 *      ANY     Ensure that the write has been written once somewhere, including possibly being hinted in a non-target node.
 *      ONE     Ensure that the write has been written to at least 1 node's commit log and memory table before responding to the client.
 *      QUORUM  Ensure that the write has been written to <ReplicationFactor> / 2 + 1 nodes before responding to the client.
 *      ALL     Ensure that the write is written to <code>&lt;ReplicationFactor&gt;</code> nodes before responding to the client.
 *
 * Read:
 *      ZERO    Not supported, because it doesn't make sense.
 *      ANY     Not supported. You probably want ONE instead.
 *      ONE     Will return the record returned by the first node to respond. A consistency check is always done in a
 *              background thread to fix any consistency issues when ConsistencyLevel.ONE is used. This means subsequent
 *              calls will have correct data even if the initial read gets an older value. (This is called 'read repair'.)
 *      QUORUM  Will query all storage nodes and return the record with the most recent timestamp once it has at least a
 *              majority of replicas reported. Again, the remaining replicas will be checked in the background.
 *      ALL     Not yet supported, but we plan to eventually.
 */
클라이언트에서 데이타를 쓰고, 읽기를 진행할때, 위의 주석에 대한 숙지가 꼭 필요할 것 같습니다. ^^

저작자 표시
Cassandra.Client는 http://incubator.apache.org/thrift/ 를 이용해서 Cassandra에 데이타를 insert하고 select하는 inner 클래스 입니다. Cassandra.Client를 생성하고 사용하기 위해서 제가 사용하는 CassandraClientFactory 클래스는 아래와 같습니다.

import org.apache.cassandra.thrift.Cassandra;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

public class CassandraClientFactory {
    private final String SERVER = "localhost";
    private final int PORT = 9160;
   
    // inner class
    private Cassandra.Client client;
    // singleton instance   
    private static CassandraClientFactory instance = new CassandraClientFactory();
   
    private CassandraClientFactory() {
        try {
            TTransport socket = new TSocket(SERVER, PORT);
            //out.println(String.format("connected to %s : %d .", SERVER, PORT));
            TBinaryProtocol binaryProtocol = new TBinaryProtocol(socket, false, false);
            this.client = new Cassandra.Client(binaryProtocol);
            socket.open();
        } catch(org.apache.thrift.transport.TTransportException e) {
            e.printStackTrace();
        }
    }
   
    public static CassandraClientFactory getInstance() {
        return instance;
    }

    public Cassandra.Client getClient() {
        return this.client;
    }
}

저작자 표시