SpringBoot で Elasticsearch クラスターを統合する方法は?
Spring BootプロジェクトにElasticsearchクラスタを統合するためには、以下の設定が必要です。
- ポン.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
- アプリケーションのプロパティ
- アプリケーションの設定ファイル「application.yml」
spring.elasticsearch.rest.uris=http://localhost:9200,http://localhost:9201,http://localhost:9202
YAML形式の設定を使用する場合、
spring:
elasticsearch:
rest:
uris: http://localhost:9200,http://localhost:9201,http://localhost:9202
- アプリケーションの設定ファイル
- アプリケーションの設定ファイル、「application.yml」
spring.elasticsearch.rest.max-connections=10
spring.elasticsearch.rest.max-per-route-connections=5
YAML形式の構成を使用してもかまいません。
spring:
elasticsearch:
rest:
max-connections: 10
max-per-route-connections: 5
- Spring Bootの設定クラスでElasticsearchのRestHighLevelClientビーンを作成して、Elasticsearchとのやり取りに使用します。
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticsearchConfig {
@Bean
public RestHighLevelClient elasticsearchClient() {
return new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http"),
new HttpHost("localhost", 9202, "http")
)
);
}
}
上記のコードを@Configurationアノテーションが付けられたクラスに配置すると、Spring Bootはそのクラス内の@Beanアノテーションが付けられたメソッドを自動的にbeanとして登録します。
Spring BootプロジェクトにElasticsearchクラスタを統合する手順は以上です。実際の要件に応じて適切な調整や最適化を行ってください。