このガイドでは、Apache Geode (英語) データ管理システムのアプリケーションを構築するプロセスについて説明します。
構築する
Spring Data for Apache Geode を使用して、POJO を格納および取得します。
必要なもの
約 15 分
お気に入りのテキストエディターまたは IDE
コードを直接 IDE にインポートすることもできます。
このガイドを完了する方法
ほとんどの Spring 入門ガイドと同様に、最初から始めて各ステップを完了するか、すでに慣れている場合は基本的なセットアップステップをバイパスできます。いずれにしても、最終的に動作するコードになります。
最初から始めるには、Spring Initializr から開始に進みます。
基本をスキップするには、次の手順を実行します。
このガイドのソースリポジトリをダウンロードして解凍するか、Git (英語) を使用してクローンを作成します。
git clone https://github.com/spring-guides/gs-accessing-data-gemfire.git (英語)
gs-accessing-data-gemfire/initial
に cd単純なエンティティを定義するにジャンプしてください。
完了したときは、gs-accessing-data-gemfire/complete
のコードに対して結果を確認できます。
Spring Initializr から開始
すべての Spring アプリケーションでは、Spring Initializr (英語) から始める必要があります。Spring Initializr は、アプリケーションに必要なすべての依存関係をすばやく取り込む方法を提供し、多くのセットアップを行います。この例では、「Spring forApacheGeode」の依存関係が必要です。
次のリストは、Maven を使用する場合の pom.xml
ファイルの例を示しています。
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.1</version> </parent> <groupId>org.springframework</groupId> <artifactId>gs-accessing-data-gemfire</artifactId> <version>0.1.0</version> <properties> <spring-shell.version>1.2.0.RELEASE</spring-shell.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-geode</artifactId> </dependency> <dependency> <groupId>org.springframework.shell</groupId> <artifactId>spring-shell</artifactId> <version>${spring-shell.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
次のリストは、Gradle を使用する場合の build.gradle
ファイルの例を示しています。
plugins { id 'org.springframework.boot' version '2.4.1' id 'io.spring.dependency-management' version '1.0.8.RELEASE' id "io.freefair.lombok" version "5.3.0" id 'java' } apply plugin: 'eclipse' apply plugin: 'idea' group = "org.springframework" version = "0.1.0" sourceCompatibility = 1.8 targetCompatibility = 1.8 repositories { mavenCentral() } dependencies { implementation "org.springframework.boot:spring-boot-starter" implementation "org.springframework.data:spring-data-geode" implementation "org.projectlombok:lombok" runtimeOnly "org.springframework.shell:spring-shell:1.2.0.RELEASE" } bootJar { baseName = 'gs-accessing-data-gemfire' version = '0.1.0' }
単純なエンティティを定義する
Apache Geode は、データをリージョンにマップするインメモリデータグリッド(IMDG)です。クラスター内の複数のノード間でデータを分割および複製する分散リージョンを構成することができます。ただし、このガイドでは LOCAL
リージョンを使用するため、サーバーのクラスター全体など、余分なものを設定する必要はありません。
Apache Geode はキー / 値ストアであり、リージョンは java.util.concurrent.ConcurrentMap
インターフェースを実装します。リージョンを java.util.Map
のように扱うことはできますが、データがリージョン内で分散、複製、一般的に管理されるため、単純な Java Map
よりもかなり洗練されています。
この例では、いくつかのアノテーションのみを使用して、Person
オブジェクトを Apache Geode(リージョン)に格納します。
src/main/java/hello/Person.java
package hello;
import java.io.Serializable;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.gemfire.mapping.annotation.Region;
import lombok.Getter;
@Region(value = "People")
public class Person implements Serializable {
@Id
@Getter
private final String name;
@Getter
private final int age;
@PersistenceConstructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return String.format("%s is %d years old", getName(), getAge());
}
}
ここには、name
と age
の 2 つのフィールドを持つ Person
クラスがあります。また、新しいインスタンスを作成するときにエンティティを設定するための単一の永続的なコンストラクターがあります。このクラスはプロジェクト Lombok (英語) を使用して実装を簡素化します。
このクラスには @Region("People")
アノテーションが付けられていることに注意してください。Apache Geode がこのクラスのインスタンスを格納すると、「People」リージョン内に新しいエントリが作成されます。このクラスは、name
フィールドを @Id
でマークします。これは、ApacheGeode 内の Person
データを識別および追跡するために使用される識別子を示します。基本的に、@Id
アノテーション付きフィールド(例: name
)はキーであり、Person
インスタンスはキー / 値エントリの値です。Apache Geode には自動化されたキー生成がないため、エンティティを Apache Geode に永続化する前に、ID(つまり、name
)を設定する必要があります。
次の重要な部分は、その人の年齢です。このガイドの後半で、これを使用してクエリを作成します。
オーバーライドされた toString()
メソッドは、人の名前と年齢を出力します。
簡単なクエリを作成する
Apache Geode 用の Spring Data は、Spring を使用した ApacheGeode でのデータの保存とアクセスに重点を置いています。また、クエリを派生させる機能など、Spring Data Commons プロジェクトから強力な機能を継承します。基本的に、Apache Geode(OQL)のクエリ言語を学ぶ必要はありません。いくつかのメソッドを作成するだけで、フレームワークによってクエリが作成されます。
これがどのように機能するかを確認するには、ApacheGeode に格納されている Person
オブジェクトを照会するインターフェースを作成します。
src/main/java/hello/PersonRepository.java
package hello;
import org.springframework.data.gemfire.repository.query.annotation.Trace;
import org.springframework.data.repository.CrudRepository;
public interface PersonRepository extends CrudRepository<Person, String> {
@Trace
Person findByName(String name);
@Trace
Iterable<Person> findByAgeGreaterThan(int age);
@Trace
Iterable<Person> findByAgeLessThan(int age);
@Trace
Iterable<Person> findByAgeGreaterThanAndAgeLessThan(int greaterThanAge, int lessThanAge);
}
PersonRepository
を有するリポジトリ作品、すなわち、それぞれ Person
と String
、その Spring Data Commons 値と ID(キー)の両方のためのジェネリック型パラメーターの指定タイプから CrudRepository
インターフェースを継承します。すぐに使用できるこのインターフェースには、基本的な CRUD(CREATE、READ UPDATE、DELETE)および単純なクエリ(例: findById(..)
)データアクセス操作を含む多くの操作が付属しています。
メソッドシグネチャーを宣言するだけで、必要に応じて他のクエリを定義できます。この場合、findByName
を追加します。これは、本質的に型 Person
のオブジェクトを検索し、name
で一致するオブジェクトを見つけます。
あなたも持っています:
findByAgeGreaterThan
は、特定の年齢以上の人を見つけるfindByAgeLessThan
は、特定の年齢未満の人を見つける特定の年齢層の人々を見つける
findByAgeGreaterThanAndAgeLessThan
これを接続して、どのように見えるか見てみましょう!
アプリケーションクラスを作成する
ここで、すべてのコンポーネントを含む Application クラスを作成します。
src/main/java/hello/Application.java
package hello;
import static java.util.Arrays.asList;
import static java.util.stream.StreamSupport.stream;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.gemfire.config.annotation.ClientCacheApplication;
import org.springframework.data.gemfire.config.annotation.EnableEntityDefinedRegions;
import org.springframework.data.gemfire.repository.config.EnableGemfireRepositories;
@SpringBootApplication
@ClientCacheApplication(name = "AccessingDataGemFireApplication")
@EnableEntityDefinedRegions(
basePackageClasses = Person.class,
clientRegionShortcut = ClientRegionShortcut.LOCAL
)
@EnableGemfireRepositories
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
ApplicationRunner run(PersonRepository personRepository) {
return args -> {
Person alice = new Person("Adult Alice", 40);
Person bob = new Person("Baby Bob", 1);
Person carol = new Person("Teen Carol", 13);
System.out.println("Before accessing data in Apache Geode...");
asList(alice, bob, carol).forEach(person -> System.out.println("\t" + person));
System.out.println("Saving Alice, Bob and Carol to Pivotal GemFire...");
personRepository.save(alice);
personRepository.save(bob);
personRepository.save(carol);
System.out.println("Lookup each person by name...");
asList(alice.getName(), bob.getName(), carol.getName())
.forEach(name -> System.out.println("\t" + personRepository.findByName(name)));
System.out.println("Query adults (over 18):");
stream(personRepository.findByAgeGreaterThan(18).spliterator(), false)
.forEach(person -> System.out.println("\t" + person));
System.out.println("Query babies (less than 5):");
stream(personRepository.findByAgeLessThan(5).spliterator(), false)
.forEach(person -> System.out.println("\t" + person));
System.out.println("Query teens (between 12 and 20):");
stream(personRepository.findByAgeGreaterThanAndAgeLessThan(12, 20).spliterator(), false)
.forEach(person -> System.out.println("\t" + person));
};
}
}
構成では、@EnableGemfireRepositories
アノテーションを追加する必要があります。
デフォルトでは、
@EnableGemfireRepositories
は現在のパッケージをスキャンして、Spring Data のリポジトリインターフェースの 1 つを継承するインターフェースを探します。basePackageClasses = MyRepository.class
を使用して、Spring Data for Apache Geode に、アプリケーション固有のリポジトリ拡張機能についてタイプごとに異なるルートパッケージをスキャンするように安全に指示します。
すべてのデータを保存するには、1 つ以上のリージョンを含む ApacheGeode キャッシュが必要です。そのためには、Apache Geode の便利な構成ベースのアノテーションに Spring Data の 1 つを使用します: @ClientCacheApplication
、@PeerCacheApplication or `@CacheServerApplication
。
Apache Geode は、クライアント / サーバー、ピアツーピア(p2p)、さらには WAN 配置などのさまざまなキャッシュトポロジをサポートします。p2p では、ピアキャッシュインスタンスがアプリケーションに埋め込まれ、アプリケーションはピアキャッシュメンバーとしてクラスターに参加することができます。ただし、アプリケーションはクラスター内のピアメンバーであるというすべての制約を受けるため、これは、たとえばクライアント / サーバートポロジほど一般的には使用されません。
この例では、@ClientCacheApplication
を使用して「クライアント」キャッシュインスタンスを作成します。これは、サーバーのクラスターに接続して通信する機能を備えています。ただし、物事を単純にするために、クライアントはサーバーをセットアップしたり実行したりせずに、LOCAL
クライアントリージョンを使用してデータをローカルに保存するだけです。
ここで、SDG マッピングアノテーション @Region("People")
を使用して Person
を「People」という領域に保存するようにタグ付けした方法を思い出してください。ここでその領域を定義するには、ClientRegionFactoryBean<String, Person>
Bean 定義を使用します。定義したばかりのキャッシュのインスタンスを挿入すると同時に、「People」という名前を付ける必要があります。
Apache Geode キャッシュインスタンス(ピアまたはクライアント)は、データを格納するリージョンの単なるコンテナーです。キャッシュは RDBMS のスキーマ、リージョンはテーブルと考えることができます。ただし、キャッシュは他の管理機能も実行して、すべてのリージョンを制御および管理します。 |
タイプは <String, Person> で、キータイプ(String )と値タイプ(Person )を一致させます。 |
public static void main
メソッドは、Spring Boot の SpringApplication.run()
を使用してアプリケーションを起動し、アプリケーションの Spring Data リポジトリを使用して Apache Geode でデータアクセス操作を実行する ApplicationRunner
(別の Bean 定義)を呼び出し ます。
アプリケーションは、定義した PersonRepository
のインスタンスをオートワイヤーします。Apache Geode 用の Spring Data は、このインターフェースを実装する具象クラスを動的に作成し、インターフェースの義務を果たすために必要なクエリコードをプラグインします。このリポジトリインスタンスは、機能を示すために run()
メソッドによって使用されます。
データの保存と取得
このガイドでは、3 つのローカル Person
オブジェクト、アリス、ベビー Bob、ティーンキャロルを作成しています。最初は、それらはメモリにのみ存在します。作成したら、ApacheGeode に保存する必要があります。
ここで、いくつかのクエリを実行します。最初は名前で全員を検索します。次に、いくつかのクエリを実行して、すべて年齢属性を使用して、大人、赤ちゃん、10 代の若者を検索します。ロギングを有効にすると、ApacheGeode の Spring Data がユーザーに代わって書き込むクエリを確認できます。
@ClientCacheApplication アノテーションの logLevel 属性を「config」に変更して、SDG によって生成される Apache GeodeOQL クエリを表示します。クエリメソッド(findByName など)には SDG の @Trace アノテーションが付けられているため、Apache Geode の OQL クエリトレース(クエリレベルのログ)がオンになり、生成された OQL、実行時間、ApacheGeode インデックスがクエリで使用されたかどうかが表示されます。結果、およびクエリによって返される行数を収集します。 |
実行可能 JAR を構築する
コマンドラインから Gradle または Maven を使用してアプリケーションを実行できます。必要なすべての依存関係、クラス、リソースを含む単一の実行可能 JAR ファイルを構築して実行することもできます。実行可能な jar を構築すると、開発ライフサイクル全体、さまざまな環境などで、アプリケーションとしてサービスを簡単に提供、バージョン管理、デプロイできます。
Gradle を使用する場合、./gradlew bootRun
を使用してアプリケーションを実行できます。または、次のように、./gradlew build
を使用して JAR ファイルをビルドしてから、JAR ファイルを実行できます。
Maven を使用する場合、./mvnw spring-boot:run
を使用してアプリケーションを実行できます。または、次のように、./mvnw clean package
で JAR ファイルをビルドしてから、JAR ファイルを実行できます。
ここで説明する手順は、実行可能な JAR を作成します。クラシック WAR ファイルを作成することもでき ます 。 |
次のようなものが表示されるはずです(クエリのようなものもあります):
Before linking up with {apache-geode-name}... Alice is 40 years old. Baby Bob is 1 years old. Teen Carol is 13 years old. Lookup each person by name... Alice is 40 years old. Baby Bob is 1 years old. Teen Carol is 13 years old. Adults (over 18): Alice is 40 years old. Babies (less than 5): Baby Bob is 1 years old. Teens (between 12 and 20): Teen Carol is 13 years old.
要約
おめでとう! Apache Geode キャッシュクライアントをセットアップし、単純なエンティティを保存し、クイッククエリを開発しました。
関連事項
次のガイドも役立ちます。
新しいガイドを作成したり、既存のガイドに貢献したいですか? 投稿ガイドラインを参照してください: GitHub (英語) 。
すべてのガイドは、コード用の ASLv2 ライセンス、およびドキュメント用の Attribution、NoDerivatives クリエイティブコモンズライセンス (英語) でリリースされています。 |