'apache project'에 해당되는 글 30건

  1. Cassandra에서 설정으로 사용하는 YAML 포맷에 대해서.. (1) 2011/11/12
  2. Cassandra와 Hadoop, HBase, MongoDB와의 차이점.. 2011/11/08
  3. Cassandra를 사용하기 전에 읽어보면 좋을 파일들.. 2011/07/19
  4. ubuntu에서 thrift0.6.1 설치하기.. 2011/07/15
  5. org.apache.cassandra.db.marshal.MarshalException: cannot parse 'xxx' as hex bytes 에러시.. 2011/06/29
  6. mybatis의 SqlSession에서 commit();close(); vs close(); 어떤걸 해야 하나요? 2011/04/29
  7. ibatis/mybatis에서 oracle connection detect 하기.. 2011/01/11
  8. Cassandra.Client 풀링하기.. (2) 2010/12/01
  9. Cassandra simple insert/get 하기.. (2) 2010/11/28
  10. Cassandra에 대한 좋은 설명과 예제들.. 2010/10/14
  11. java.lang.IllegalArgumentException: Mapped Statements collection does not contain value xxx.xxx.xxx.xxx 2010/09/13
  12. 톰캣 웹 어플리케이션의 클래스 패스.. 2010/08/24
  13. tomcat 하위 버전의 memory leak에 대한 내용.. 2010/07/20
  14. Cassandra 정리문서 및 테스트 결과 2010/07/13
  15. Cassandra 발표 자료 2010/07/06
  16. ConsistencyLevel에 대해서.. 2010/07/02
  17. ClusterName 바꿔서 발생한 오류.. 2010/06/18
  18. Cassandra.Client 생성을 클래스 예제 2010/06/16
  19. mssql 2008 jdbc 세팅하기.. 2010/06/11
  20. httpclient를 이용한 웹 페이지 EUC-KR 인코딩 문제 2010/02/08
  21. Struts 1.0 Vs Struts 2.0 2008/09/26
  22. Application Server(Tomcat)의 효과적인 운영 방안 2008/08/01
  23. Apache iBatis에서 다중 데이터 베이스 사용 방법 2008/08/01
  24. Tomcat 버전별 클래스 로딩 순서 2008/06/10
  25. IBatis에서 MSSQL의 여러개 카탈로그에 접속하기 2008/06/10
카산드라는 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 파일의 이슈트래킹 번호를 따라 들어가게 되면, 버전 업에 따른 좀 더 세부적인 내용을 살펴볼 수 있습니다.. 


이상, 카산드라를 무작정 사용하는 것도 좋겠지만, 한번 읽어보면 좋을 만한 카산드라 파일에 대한 내용이었습니다.. ^^ 
저작자 표시
1. 필요한 패키지를 설치한다.
sudo apt-get install libboost-dev libboost-test1.42-dev libboost-program-options1.42-dev libevent-dev automake libtool flex bison pkg-config g++

1.1 위의 내용은 http://wiki.apache.org/thrift/GettingUbuntuPackages 에서..

2. 소스를 다운로드 받아서 압축을 푼다.
$ tar xvf thrift-0.6.1.tar.gz
 
3. 컴파일하고 설치한다.
$ cd thrift-0.6.1/
$ ./configure JAVAC=/usr/local/java --prefix=/usr/local/thrift
$ make
$ sudo make install

저작자 표시
아.. 
오랜만에 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; 


저작자 표시
코드를 보다보니, 아래와 같은 코드가 있어서 확인해 봤습니다.. ^^;;

try {
session = createSqlSession();
// db 처리.. .
} finally {
// db 세션 종료
if(session != null) {
session.commit();
session.close();
}
}

그래서, http://code.google.com/p/mybatis/source/browse/tags/mybatis-3.0.4/src/main/java/org/apache/ibatis/session/defaults/DefaultSqlSession.java 의 session코드에서 commit메쏘드와 close메쏘드를 살펴 봤습니다..

* commit() : 오버로딩하는 두개의 메쏘드가 있네요.. ^^
  public void commit() {
    commit(false);
  }

  public void commit(boolean force) {
    try {
      executor.commit(isCommitOrRollbackRequired(force));
      dirty = false;
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error committing transaction.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

* close()
  public void close() {
    try {
      executor.close(isCommitOrRollbackRequired(false));
      dirty = false;
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error closing transaction.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

위 코드를 보시면, commit();close(); 코드와 close();가 있습니다..
코드를 따라가다 보면, 결국, http://code.google.com/p/mybatis/source/browse/tags/mybatis-3.0.4/src/main/java/org/apache/ibatis/transaction/jdbc/JdbcTransaction.java 에서, 아래와 같은 코드를 볼 수 있습니다.

  public void commit() throws SQLException {
    if (!connection.getAutoCommit()) {
      connection.commit();
    }
  }

  public void close() throws SQLException {
    resetAutoCommit();
    connection.close();
  }

  protected void resetAutoCommit() {
    try {
      if (!connection.getAutoCommit()) {
        // for compatibility we always use true, as some drivers don't like being left in "false" mode.
        connection.setAutoCommit(true);
      }
    } catch (SQLException e) {
      // Only a very poorly implemented driver would fail here,
      // and there's not much we can do about that.
      throw new TransactionException("Error configuring AutoCommit.  " +
          "Your driver may not support getAutoCommit() or setAutoCommit(). Cause: " + e, e);
    }
  }

흠, 따라서 commit();close();와 close();가 동일할 거라는 심증만 가지게 되네요..^^;;
commit();close();해야 하나요?? close();만 하면 되까요?? ㅋㅋ
저작자 표시
http://novathin.kr/님께서 알려준, 오라클 db conn detect할 수 있는 옵션입니다.
<dataSource type="POOLED"> 안에 아래의 property를 넣어주면 됩니다..
<property name="poolPingEnabled" value="true"/>
<property name="poolPingQuery" value="select 1 from dual"/>
아, 좋네요.. ^^
저작자 표시

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
위와 같은 에러가 나올경우..
흠.. 알면 쉬운데.. 왜 나는지 정확하게 모르면 엄청 고생하게 되네요..

위 내용은 Mapper에 선언되어 있는 메쏘드 이름과 mapper 파일의 select나 insert등의 이름과 일치하지 않아서 발생합니다.. 아래 처럼 말이죠.. ^^;;

ex) 인터페이스 이름
public String print(String x) throws Exception;

ex) mapper.xml
<select id="prints" statementType="CALLABLE" parameterType="String" resultType="String">
        .........................
</select>


저작자 표시
Tag // iBATIS, Mapper, mybatis
웹 어플리케이션들은 보통 아래의 구조를 가지고 있습니다.

WEB-INF
  -lib
  -classes

그리고, 각 어플리케이션마다 별도의 클래스 로더가 클래스들을 로딩합니다..
그런데.. 위의 lib 폴더는 클래스 패스로 안 잡네요.. ^^;;
어쩐지, 각종 프레임웍들의 설정파일들이 classes 폴더에 넣는 이유가 있었네요.. ^^;;

저작자 표시
이것도 문서를 정리하다가 발견했네요. ^^

1. 톰캣 메모리 릭 : http://java.dzone.com/articles/memory-leak-protection-tomcat
 웹 어플리케이션을 로딩할때, 클래스 로더가 각 어플리케이션별로 세팅이 되고, 이 로더가 클래스를 다시 로딩하면서 기존의 클래스들에 대한 reference를 클래스 로더가 유지를 하고 있어서 eden 영역의 메모리가 차는 현상이 발견. 결과로 OutOfMemory Error

2. 패치 : 7.0대 버전에서 발견되서, 6.0.24  버전(http://mirror.khlug.org/apache/tomcat/tomcat-6/v6.0.24/RELEASE-NOTES)에 반영
저작자 표시
보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.
카산드라에 대한 내용 정리 자료입니다...
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;
    }
}

저작자 표시
mssql 2008을 ibatis에서 사용하기 위한 세팅입니다.
흠.. mssql을 잘 몰라서 포트 세팅하는데 힘들었네요.. ^^;;
전에는 default port가 1433이었는데..

Sql Server Configuration Manager --> SQL Server 네트워크 구성 --> TCP/IP 사용의 속성창을 보시면 아래의 화면이 나옵니다.. 그리고 TCP 동적포트로 접근을 하시면 됩니다.. ^^;;



<sqlMapConfig>
    <transactionManager type="JDBC" commitRequired="false">
        <dataSource type="SIMPLE">
            <property name="JDBC.Driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
            <property name="JDBC.ConnectionURL" value="jdbc:sqlserver://computer-name\SQLEXPRESS:4147;databaseName=testdb;integratedSecurity=true;"/>
            <property name="JDBC.Username" value="id"/>
            <property name="JDBC.Password" value="password"/>
            <property name="Pool.MaximumIdleConnections" value="5"/>
            <property name="Pool.MaximumCheckoutTime" value="120000"/>
            <property name="Pool.TimeToWait" value="500"/>
        </dataSource>
    </transactionManager>
    <sqlMap resource="article.xml"/>
</sqlMapConfig>

그리고, 혹시  경고: Failed to load the sqljdbc_auth.dll 메세지를 뿌르게 되면..
플랫폼에 맞는 sqljdbc_auth.dl를 windows\system32폴더에 카피를 하시면 됩니다. 
HTTP 프로토콜을 이용한 요청/응답을 쉽게 가능하게 도와주는 라이브러리로 Apache HttpClient를 사용해 봤습니다. 흠.. UTF-8등은 문제가 되지 않지만, EUC-KR로 인코딩된 페이지는 한글이 깨져서 나옵니다.


위 문제를 해결하기 위해서는 받은 데이타를 맞는 포맷으로 인코딩해 주시면 됩니다.
아래 코드처럼, 받은 데이타를 String 변수인 x에 저장하고, 다시 x를 아래의 포맷(iso-8859-1)으로 바꿔서 String y에 저장을 하고 뿌려주면 아래그림처럼 잘 나오게 됩니다.

String y = new String(x.getBytes("iso-8859-1"));

아래 내용은 http://www.javabeat.net/tips/139-struts-10-vs-struts-20.html의 내용입니다.

Difference between Struts 1.0 and Struts 2.0

In the following section, we are going to compare the various features between the two frameworks. Struts 2.0 is very simple as compared to struts 1.0,1.1, few of its excelent features are:

1.Servlet Dependency

Actions in Struts1 have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse objects are passed to the execute method when an Action is invoked but in case of Struts 2.0, Actions are not container dependent because they are made simple POJOs. In Struts 2.0, the servlet contexts are represented as simple Maps which allows actions to be tested in isolation. Struts 2.0 Actions can access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly.

2.Action classes

Programming the abstract classes instead of interfaces is one of design issues of struts 1.0 framework that has been resolved in the Struts 2.0 framework. Struts 1.0 Action classes needs to extend framework dependent abstract base class. But in case of Struts 2.0 Action class may or may not implement interfaces to enable optional and custom services. In case of Struts 2.0 , Actions are not container dependent because they are made simple POJOs. Struts 2.0 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with an execute signature can be used as an Struts 2.0 Action object.

3.Validation

Struts 1.0 and Struts 2.0 both supports the manual validation via a validate method. Struts 1.0 uses validate method on the ActionForm, or validates through an extension to the Commons Validator. However, Struts 2.0 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.

4.Threading Model

In Struts1, Action resources must be thread-safe or synchronized. So Actions are singletons and thread-safe, there should only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts 1.0 Actions and requires extra care to develop. However in case of Struts 2.0, Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)

5.Testability

Testing Struts 1.0 applications are a bit complex. A major hurdle to test Struts 1.0 Actions is that the execute method because it exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts1. But the Struts 2.0 Actions can be tested by instantiating the Action, setting properties and invoking methods. Dependency Injection support also makes testing simpler. Actions in struts2 are simple POJOs and are framework independent, hence testability is quite easy in struts2.

6.Harvesting Input

Struts 1.0 uses an ActionForm object to capture input. And all ActionForms needs to extend a framework dependent base class. JavaBeans cannot be used as ActionForms, so the developers have to create redundant classes to capture input. However Struts 2.0 uses Action properties (as input properties independent of underlying framework) that eliminates the need for a second input object, hence reduces redundancy. Additionally in Struts 2.0, Action properties can be accessed from the web page via the taglibs. Struts 2.0 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Even rich object types, including business or domain objects, can be used as input/output objects.

7.Expression Language

Struts 1.0 integrates with JSTL, so it uses the JSTL-EL. The struts1 EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2.0 can also use JSTL, however it supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).

8.Binding values into views

In the view section, Struts1 uses the standard JSP mechanism to bind objects (processed from the model section) into the page context to access. However Struts 2.0 uses a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows the reuse of views across a range of types which may have the same property name but different property types.

9.Type Conversion

Usually, Struts 1.0 ActionForm properties are all Strings. Struts 1.0 uses Commons-Beanutils for type conversion. These type converters are per-class and not configurable per instance. However Struts 2.0 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.

10.Control Of Action Execution

Struts 1.0 supports separate Request Processor (lifecycles) for each module, but all the Actions in a module must share the same lifecycle. However Struts 2.0 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions as needed.


'Apache Project > Struts 2.x' 카테고리의 다른 글

Struts 1.0 Vs Struts 2.0  (0) 2008/09/26
struts2 dtd 파일입니다.  (0) 2008/04/28
struts2 아키텍처 입니다.  (0) 2008/03/02
.action 확장자를 원하는 형태로 바꿔보자...  (0) 2008/03/02
1. 어플리케이션 서버에서 필요한 메모리 계산 방법
 - 계산식 : (MaxProcessMemory - JVMMemory - ReservedOsMemory) / (ThreadStackSize) = Number of threads
 - 메모리 계산 예
가정 : Java 1.5를 사용중이며 OS가 120MB를, 디폴트 스택사이즈는 0.5M
  • JVM에 1.5GB할당되었을 경우 : (2GB-1.5Gb-120MB)/(1MB) = ~380 threads
  • JVM에 1.0GB할당되었을 경우 : (2GB-1.0Gb-120MB)/(1MB) = ~880 threads
통계적으로 대략 200명의 동시 사용자 수용할 경우 300MB정도 필요하합니다. 이것을 고려해서 메모리를 계산하면 됩니다.

2. Application Server 에러 대처 방안(java.lang.OutOfMemoryError: PermGen space 현상)
  • Tomcat의 경우 v6.0.14이상의 안정적 릴리즈 된것을 선택
  • JDK1.4보다는 1.5, 1.6의 사용을 권고함
  • -XXMaxPermSize 설정을 통해 perm 사이즈를 증가시킴
  • JHat으로 메모리릭 원인을 찾고 JConsole, Lambda probe 등을 통해 메모리 모니터링을 함
  • Application Server운영자는 Garbage Collection에 대한 이해가 있어야 함

3. Tomcat에서 설정 예시

  • 힙메모리 정보를 출력 : -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintHeapAtGC

위 설정을 통해 출력되는 로그를 보고 New Generation의 eden 영역, Old Generation 영역, Permanent 영역을 확인하여 각 영역이 작으면 아래와 같은 설정으로 적당 사이즈를 확보해 줍니다.

  • 도출된 설정 : -Xms256m -Xmx512m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:MaxPermSize=128m -XX:SurvivorRatio=5
    -Xms : 최소 힙 싸이즈
    -Xmx : 최대 힙 싸이즈
    -XX:NewSize : New Generation의 최소 싸이즈
    -XX:MaxNewSize : New Generation의 최대 싸이즈
    -XX:MaxPermSize : Permanent Generation의 최대 싸이즈 가 되겠다.
    -XX:SurvivorRatio : 영역비율(New Generation)

결론적으로 적용할 설정은 아래와 같습니다.

  • CATALINA_OPTS="-server -Xss256k -Xms256m -Xmx512m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:MaxPermSize=128m -XX:SurvivorRatio=5 -XX:ReservedCodeCacheSize=128m -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -Djava.net.preferIPv4Stack=true -Djava.awt.headless=true "

Open Soure는 100% 안정적이지 않기 때문에 가장 최신의 안정적인 버젼이 릴리즈되는지 항상 예의 주시하여 버전업에 게을러서는 안됩니다

위 내용은 http://www.mimul.com/pebble/default/2008/01/26/1201346400000.html 에서 발췌를 하였습니다.

Apache iBatis에서 다중의 데이타 베이스에 접속하는 방법에 대한 내용입니다.

1. database.properties

driver=oracle.jdbc.driver.OracleDriver
jdbc.url1=jdbc:oracle:thin:@mimuluserdb:1521:mimuluser
username1=mimuluser
password1=mimuluser

jdbc.url2=jdbc:oracle:thin:@pepsiuserdb:1521:pepsiuser
username2=pepsiuser
password2=pepsiuser

2. sqlmap1.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
        PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
        "http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
    <properties resource="com/mimul/dwr/app/
               resource/database.properties"/>
    <settings
            cacheModelsEnabled="true"
            enhancementEnabled="true"
            lazyLoadingEnabled="true"
            maxRequests="40"
            maxSessions="20"
            maxTransactions="5"
            useStatementNamespaces="false"
            />
    <transactionManager type="JDBC">
        <dataSource type="DBCP">
            <property name="driverClassName" value="${driver}"/>
            <property name="url" value="${jdbc.url1}"/>
            <property name="username" value="${username1}"/>
            <property name="password" value="${password1}"/>

            <!-- OPTIONAL PROPERTIES BELOW -->
            <property name="initialSize" value="5"/>
            <property name="maxActive" value="30"/>
            <property name="maxIdle" value="20"/>
            <property name="maxWait" value="60000"/>
            <property name="poolPreparedStatements" value="true"/>
            <property name="validationQuery" value="select 0 from dual"/>
            <property name="testOnBorrow" value="true"/>
            <property name="maximumActiveConnections" value="10"/>
            <property name="maximumIdleConnections" value="5"/>
            <property name="maximumWait" value="60000"/>
            <property name="logAbandoned" value="false"/>
            <property name="removeAbandoned" value="false"/>
            <property name="removeAbandonedTimeout" value="50000"/>
        </dataSource>
    </transactionManager>
    <sqlMap resource="com/mimul/dwr/app/sql/Mimul.xml"/>
</sqlMapConfig>

3. sqlmap2.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
        PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
        "http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
    <properties resource="com/mimul/dwr/app/resource/database.properties"/>
    <settings
            cacheModelsEnabled="true"
            enhancementEnabled="true"
            lazyLoadingEnabled="true"
            maxRequests="40"
            maxSessions="20"
            maxTransactions="5"
            useStatementNamespaces="false"
            />
    <transactionManager type="JDBC">
        <dataSource type="DBCP">
            <property name="driverClassName" value="${driver}"/>
            <property name="url" value="${jdbc.url2}"/>
            <property name="username" value="${username2}"/>
            <property name="password" value="${password2}"/>

            <!-- OPTIONAL PROPERTIES BELOW -->
            <property name="initialSize" value="5"/>
            <property name="maxActive" value="30"/>
            <property name="maxIdle" value="20"/>
            <property name="maxWait" value="60000"/>
            <property name="poolPreparedStatements" value="true"/>
            <property name="validationQuery" value="select 0 from dual"/>
            <property name="testOnBorrow" value="true"/>
            <property name="maximumActiveConnections" value="10"/>
            <property name="maximumIdleConnections" value="5"/>
            <property name="maximumWait" value="60000"/>
            <property name="logAbandoned" value="false"/>
            <property name="removeAbandoned" value="false"/>
            <property name="removeAbandonedTimeout" value="50000"/>
        </dataSource>
    </transactionManager>
    <sqlMap resource="com/mimul/dwr/app/sql/Pepsi.xml"/>
</sqlMapConfig>

4. SqlCondig.java

import java.io.File;
import java.io.Reader;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.jaeminara.common.log.LogPool;

public class SqlConfig {
    private static SqlMapClient sqlMap1 = null;
    private static SqlMapClient sqlMap2 = null;
    private static SqlConfig instance_ = null;
   
    private SqlConfig() throws Exception {
        Reader reader = null;
        String resource = null;
        try {
            if (sqlMap == null) {
                resource = "sqlmap1.xml";
              reader = Resources.getResourceAsReader(resource);
              sqlMap1 = SqlMapClientBuilder.buildSqlMapClient(reader);
                resource = "sqlmap2.xml";
              reader = Resources.getResourceAsReader(resource);
              sqlMap2 = SqlMapClientBuilder.buildSqlMapClient(reader);
              reader.close();
            }
        } catch (Exception e) {
            System.out.println(e);
            throw e;
        } finally {
            if (reader != null)
                reader.close();
            reader = null;
            rsc = null;
        }
    }
   
    public static SqlConfig instance() {
        try {
            if (instance_ == null) {
                synchronized (SqlConfig.class) {
                    if (instance_ == null)
                        instance_ = new SqlConfig();
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return instance_;
    }

    /**
     * Return SqlMapClient for SDP schema
     *
     * @return
     */
    public static SqlMapClient getSqlMap1Instance() {
        return sqlMap1;
    }

    /**
     * Return SqlMapClient for SDP schema
     *
     * @return
     */
    public static SqlMapClient getSqlMap2Instance() {
        return sqlMap2;
    }
}

이 내용은 http://mimul.com/pebble/default/2008/02/24/1203779580000.html 에서 발췌를 하였습니다.
Tomcat5.5 클래스 로딩 순서

Bootstrap classes of your JVM
System class loader classses (described above)
/WEB-INF/classes of your web application
/WEB-INF/lib/*.jar of your web application
$CATALINA_HOME/common/classes
$CATALINA_HOME/common/endorsed/*.jar
$CATALINA_HOME/common/i18n/*.jar
$CATALINA_HOME/common/lib/*.jar
$CATALINA_BASE/shared/classes
$CATALINA_BASE/shared/lib/*.jar

Tomcat5.0 클래스로딩 순서

Bootstrap classes of your JVM
System class loader classses (described above)
/WEB-INF/classes of your web application
/WEB-INF/lib/*.jar of your web application
$CATALINA_HOME/common/classes
$CATALINA_HOME/common/endorsed/*.jar
$CATALINA_HOME/common/lib/*.jar
$CATALINA_BASE/shared/classes
$CATALINA_BASE/shared/lib/*.jar

Tomcat4.1 클래스로딩 순서

/WEB-INF/classes of your web application
/WEB-INF/lib/*.jar of your web application
Bootstrap classes of your JVM
System class loader classses (described above)
$CATALINA_HOME/common/classes
$CATALINA_HOME/common/endorsed/*.jar
$CATALINA_HOME/common/lib/*.jar
$CATALINA_BASE/shared/classes
$CATALINA_BASE/shared/lib/*.jar

출처 : http://www.jakartaproject.com/article/jsptip/111456818395700

에고...
IBatis에서 MSSQL2000 인스턴스의 카탈로그에 접속하기 위해서 한참을 헤메서 겨우 찾았네요.. ^^;;

아래는 해결책입니다.. ^^;;

해결책은 인스턴스의 실제 TCP 포트로 접속하면 됩니다.. ^^;;
넘 간단한가?? ㅋㅋ