본문 바로가기

빅데이터/cassandra

macos에서 카산드라 테스트 방법

https://cassandra.apache.org/_/quickstart.html

 

Apache Cassandra | Apache Cassandra Documentation

STEP 4: LOAD DATA WITH CQLSH The CQL shell, or cqlsh, is one tool to use in interacting with the database. We’ll use it to load some data into the database using the script you just saved. docker run --rm --network cassandra -v "$(pwd)/data.cql:/scripts/

cassandra.apache.org

 

macos에서 docker 이미지를 사용하여 카산드라를 실행하고 테스트할 수 있습니다.

여기서는 docker가 아닌 podman을 활용하여 카산드라 이미지를 실행하여 테스트 수행해봅니다.

 

1. podman 설치,  실행

$ brew install podman
$ podman system connection list
$ podman machine start

podman은 컨테이너 관리 도구로서 docker와 유사한 기능을 가지고 있습니다. 저는 docker desktop을 설치하지 않기 때문에 podman을 사용하여 테스트를 수행합니다.

2. cassandra 바이너리 다운로드

카산드라 바이너리는 다음 url에서 다운로드 받을 수 있습니다.

https://cassandra.apache.org/_/download.html

 

Apache Cassandra | Apache Cassandra Documentation

Source Development is done in the Apache Git repository. To check out a copy: git clone https://gitbox.apache.org/repos/asf/cassandra.git

cassandra.apache.org

이 바이너리를 통해서 cqlsh를 실행할 수 있습니다.

3. cassandra 실행

$ podman run -p 9042:9042 -d cassandra:latest

9042 포트는 카산드라의 CQL 연동 포트입니다.

4. cqlsh 실행

카산드라 바이너리 압축을 풀면 bin디렉토리에서 cqlsh를 실행할 수 있습니다.

$ ./cqlsh  
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 4.0.1 | CQL spec 3.4.5 | Native protocol v4]
Use HELP for help.

5. cqlsh 테스트

테스트는 카산드라 홈페이지의 quickstart 페이지의 명령어를 따라 수행합니다.

https://cassandra.apache.org/_/quickstart.html

 

Apache Cassandra | Apache Cassandra Documentation

STEP 4: LOAD DATA WITH CQLSH The CQL shell, or cqlsh, is one tool to use in interacting with the database. We’ll use it to load some data into the database using the script you just saved. docker run --rm --network cassandra -v "$(pwd)/data.cql:/scripts/

cassandra.apache.org

cqlsh> CREATE KEYSPACE IF NOT EXISTS store WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : '1' };
cqlsh> CREATE TABLE IF NOT EXISTS store.shopping_cart (
   ... userid text PRIMARY KEY,
   ... item_count int,
   ... last_update_timestamp timestamp
   ... );
cqlsh> INSERT INTO store.shopping_cart
   ... (userid, item_count, last_update_timestamp)
   ... VALUES ('9876', 2, toTimeStamp(now()));
cqlsh> INSERT INTO store.shopping_cart
   ... (userid, item_count, last_update_timestamp)
   ... VALUES ('1234', 5, toTimeStamp(now()));
cqlsh> SELECT * FROM store.shopping_cart;

 userid | item_count | last_update_timestamp
--------+------------+---------------------------------
   1234 |          5 | 2021-11-03 03:02:05.215000+0000
   9876 |          2 | 2021-11-03 03:02:04.913000+0000

(2 rows)
cqlsh>  INSERT INTO store.shopping_cart (userid, item_count) VALUES ('4567', 20);
cqlsh> SELECT * FROM store.shopping_cart;

 userid | item_count | last_update_timestamp
--------+------------+---------------------------------
   4567 |         20 |                            null
   1234 |          5 | 2021-11-03 03:02:05.215000+0000
   9876 |          2 | 2021-11-03 03:02:04.913000+0000

(3 rows)

1) store라는 이름의 키스페이스를 생성합니다. 관련 옵션은 다음과 같습니다.

- class : SimpleStrategy

- replication_factor : 1

SimpleStrategy는 RackUnawareStrategy를 뜻하며, 기본값으로 복제본을 시계방향으로 다음 노드에 배치한다. 상용환경에서는 NetworkStrategy를 보통 사용한다.

 

2) store 키스페이스에 shopping_cart 테이블을 생성합니다. 해당 테이블에는 userid, item_count, last_update_timestamp 칼럼이 포함되어 있습니다.

 

3) 2번에 나누어 데이터를 insert합니다.

 

4) select 구문으로 데이터를 조회합니다.

 

6. JAVA CqlSession 테스트

build.gradle 디펜던시 추가

dependencies {
    implementation group: 'com.datastax.oss', name: 'java-driver-core', version: '4.6.1'
    implementation group: 'com.datastax.oss', name: 'java-driver-query-builder', version: '4.6.1'
    implementation group: 'com.datastax.oss', name: 'java-driver-mapper-runtime', version: '4.6.1'
}

CassandraConnector.java 작성

class CassandraConnector implements Closeable {
    private CqlSession session;

    public CassandraConnector(String ip, Integer port) {
        CqlSessionBuilder b = CqlSession.builder();
        b.addContactPoint(new InetSocketAddress(ip, port));
        b.withLocalDatacenter("datacenter1");
        session = b.build();
    }

    public CqlSession getSession() {
        return this.session;
    }

    @Override
    public void close() {
        session.close();
    }
}

Main.java 실행

public class Main {

    public static void main(String[] args) {
        try (CassandraConnector client = new CassandraConnector("127.0.0.1", 9042)) {
            CqlSession session = client.getSession();
            ResultSet result = session.execute("select * from store.shopping_cart");
            List<Row> list = result.all();
            for (Row row : list) {
                System.out.println(row.getObject(0) +"|"+ row.getObject(1) +"|"+ row.getObject(2));
            }
        }
    }
}

실행 로그

15:14:07.005 [main] INFO  c.d.o.d.i.c.DefaultMavenCoordinates - DataStax Java driver for Apache Cassandra(R) (com.datastax.oss:java-driver-core) version 4.6.1
15:14:07.618 [s0-admin-0] INFO  c.d.o.d.internal.core.time.Clock - Using native clock for microsecond precision
15:14:12.770 [s0-io-0] INFO  c.d.o.d.i.c.channel.ChannelFactory - [s0] Failed to connect with protocol DSE_V2, retrying with DSE_V1
15:14:12.776 [s0-io-1] INFO  c.d.o.d.i.c.channel.ChannelFactory - [s0] Failed to connect with protocol DSE_V1, retrying with V4
15:14:17.795 [s0-io-2] INFO  c.d.oss.driver.api.core.uuid.Uuids - PID obtained through native call to getpid(): 80177
123|0|null
4567|20|null
1234|5|2021-11-03T03:02:05.215Z
9876|2|2021-11-03T03:02:04.913Z
반응형