카산드라는 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.
 */
클라이언트에서 데이타를 쓰고, 읽기를 진행할때, 위의 주석에 대한 숙지가 꼭 필요할 것 같습니다. ^^

저작자 표시
storage-conf.xml 의  <ClusterName>을 Cluster1으로 바꾸니 에러가 나네요.. ^^;;
아래처럼요....
INFO 10:00:53,760 Saved ClusterName found: Test Cluster
ERROR 10:00:53,760 ClusterName mismatch: Test Cluster != Cluster1

storage-conf.xml의 <DataFileDirectory>에서 설정한 위치의 하위 디렉토리인 system 디렉토리의 LocationInfo 파일들 다 지우면 된다고 하네요..

저작자 표시
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;
    }
}

저작자 표시