Webエンジニアのメモ帳

技術的な話を中心に書いています。

【Spring Boot】Cassandraに接続しデータを操作する方法

Spring BootでCassandraを扱う方法を説明します。

テーブルの作成

まずは、Cassandraにテーブル(カラムファミリ)を作成します。

テーブルの内容は以下の通りです。キースペース名はcreaturesとします。

id |     name | category
---+----------+----------
1 |      dog |   animal
2 |      cat |   animal
3 |    shark |     fish

データをマッピングするクラスの作成

次に、これをマッピングするクラスを作成します。

import com.datastax.driver.mapping.annotations.Table;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;

@Table(keyspace = "test", name = "creatures")
public class Creature {
  @PartitionKey
  @Column(name = "id")
  private int id;

  @Column(name = "name")
  private String name;

  @Column(name = "category")
  private String category;
  
  # (以下、ゲッターとセッター)
}

ポイントとして、primary keyになっているカラムに対して@PartitionKeyアノテーションを付与しないとエラーになります。

また、各フィールドに対するゲッターとセッターを記述する必要があります。

この記事では解説しませんが、Lombokなどのライブラリを使って自動で生成するのがオススメです。

Cassandraの設定を記述するクラスの作成

次に、Cassandraの設定をCassandraConfiguration.javaというファイルに記述します。

なお、Cassandraにログインするためのユーザー名とパスワードは"user"と"pass"とします。

import com.datastax.driver.core.Cluster;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CassandraConfiguration {
  @Bean
  public Cluster claster() {
    Cluster cluster = Cluster.builder()
      .withoutJMXReporting()
      .addContactPoint("localhost")
      .withPort(9042)
      .withCredentials("user", "pass")
      .build();
    return cluster;
  }
}

Cassandraのデータを扱う

最後に、Cassandra上のデータを扱うクラスです。

@Repository
public class CreatureRepository {
  private final Cluster cluster;

  // コンストラクタインジェクションにより、CassandraConfiguration.javaで@Bean登録したclusterが引数に入ります。
  public ContentRepository(Cluster cluster){
    this.cluster = cluster;
  }
  @Override
  public Creature getCreature(String id) {
    Session session = cluster.connect();
    MappingManager manager = new MappingManager(session);
    Mapper<Creature> mapper = manager.mapper(Creature.class);

    // Primary Keyを指定してデータ取得
    Creature creature = mapper.get(id);
    return creature;
  }
}

あとは、サービス層のコードなどで上記のクラスのgetCreature()を呼び出せば、Cassandraからデータを取得できます。

補足

実装している途中で以下のエラーが発生し、解決に時間を使ってしまいました。

java.lang.ClassNotFoundException: com.codahale.metrics.JmxReporter

この解決法ですが、CassandraConfiguration.java

.withoutJMXReporting()

という行を書き足すことで解決できました。