AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

チュートリアル: MongoDBを使用してマイクロサービス アプリをビルドする

このチュートリアルでは、Spring Boot、Spring Cloud、およびMongoDBを使用してマイクロサービスアーキテクチャをビルドする方法を示します。具体的には、このチュートリアルでは、連携して完全なアプリケーションを作成する複数のサービスを作成する方法について説明します。

次の GitHub リポジトリに完全なソースコードを見つけることができます。

上に構築されたフレームフレームワークです。自動構成、デフォルト、本番環境に対応する機能が追加され、Spring Data MongoDBとの統合など、SpringベースのJavaアプリケーションの構築が簡素化されます。詳細については、書込み保証 (write concern) のドキュメントを参照してください。

Spring Cloud は、分散されたシステムとマイクロサービスを構築するためのツールのコレクションです。構成マネジメント、サービス検出、インテリジェント ルーティングの機能を提供します。詳細については、Spring クラウド documentation.を参照してください。

このチュートリアルでは、次のアクションを実行する方法について説明します。

  • 前提条件を確認します

  • 例リポジトリのクローン作成

  • コンフィギュレーションサーバーを設定する

  • サービス レジストリを設定する

  • APIゲートウェイの構成

  • MongoDBマイクロサービスの作成

  • REST API をテストする

1

始める前に、以下のものがインストールされていることを確認してください。

  • Java開発キット(JDK) 21 以降。JDK はOracle のウェブサイトからダウンロードできます。

  • Git

  • MongoDB (ローカル開発の 2 つの配置)。MongoDB をローカルで設定する方法については、 「Dockerを使用したローカル Atlas 配置の作成」 のガイドを参照してください。

2

次のコマンドを実行中て、マイクロサービスアプリケーションと構成リポジトリをクローンします。

git clone git@github.com:mongodb-developer/microservices-architecture-mongodb.gitgit clone git@github.com:mongodb-developer/microservices-architecture-mongodb-config-repo.git

microservices-architecture-mongodbリポジトリの README.mdファイルにある指示に従って、各サービスを起動します。

3

コンフィギュレーションサーバーは、単一のリポジトリ内にマイクロサービスのすべての構成ファイルを保存します。

コンフィギュレーションサーバーの構成は microservices-architecture-mongodb/config-server/src/main/resources/application.propertiesファイルで定義されます。

spring.application.name=config-serverserver.port=8888spring.cloud.config.server.git.uri=${HOME}/Work/microservices-architecture-mongodb-config-repospring.cloud.config.label=main

この構成では、マイクロサービス構成と使用するブランチを保存する Gitリポジトリのロケーションを指定します。

コンフィギュレーションサーバーアプリケーションは、microservices-architecture-mongodb/config-server/src/main/java/com/mongodb/configserver/ディレクトリにある次のJavaクラスで定義されています。

ConfigServer Application.java

package com.mongodb.configserver; import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.config.server.EnableConfigServer; @EnableConfigServer@SpringBootApplicationpublic class ConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); }}

注意

@EnableConfigServer アノテーションを使用すると、 アプリケーションでコンフィギュレーションサーバー機能が有効になります。

4

サービス レジストリは、実行中のマイクロサービスとそのロケーションを追跡します。他のサービスはこの情報を使用して、必要なマイクロサービスと通信します。

サービス レジストリ構成は、次の プロパティファイルで定義されます。

spring.application.name=service-registryserver.port=8761eureka.client.register-with-eureka=falseeureka.client.fetch-registry=false

最後の 2 つのプロパティは、サービス レジストリが自分自身に登録されるのを防ぎます。

サービス レジストリアプリケーションは、microservices-architecture-mongodb/service-registry/src/main/java/com/mongodb/serviceregistry/ディレクトリにある次のJavaクラスで定義されています。

ServiceRegistry Application.java

package com.mongodb.serviceregistry; import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication@EnableEurekaServerpublic class ServiceRegistryApplication { public static void main(String[] args) { SpringApplication.run(ServiceRegistryApplication.class, args); }}

注意

@EnableEurekaServer アノテーションを使用すると、 アプリケーションでサービス レジストリ機能が有効になります。

5

APIゲートウェイは、すべてのマイクロサービスにアクセスするための単一のエントリ点を提供します。ゲートウェイはリクエストを複数のマイクロサービスに分散し、セキュリティやモニタリングなどの問題を取り扱います。

APIゲートウェイの構成は microservices-architecture-mongodb/api-gateway/src/main/resources/application.ymlファイルで定義されます。

server: port: 8080 spring: application: name: api-gateway cloud: gateway: routes: - id: company-service uri: lb://company-service predicates: - Path=/api/company/**,/api/companies - id: employee-service uri: lb://employee-service predicates: - Path=/api/employee/**,/api/employees eureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eureka/ instance: hostname: localhost

この構成では、会社と従業員のサービスのルートを定義し、ゲートウェイをサービス レジストリに登録します。

6

このアプリケーションには、会社サービスと従業員サービスの 2 つのマイクロサービスが含まれています。各マイクロサービスは、独立性を維持するために、独自のMongoDBインスタンスに接続します。

会社のサービス構成は microservices-architecture-mongodb-config-repo/company-service.propertiesファイルに定義されています。

spring.data.mongodb.uri=${MONGODB_URI_1:mongodb://localhost:27017}spring.threads.virtual.enabled=truemanagement.endpoints.web.exposure.include=*management.info.env.enabled=trueinfo.app.name=Company Microserviceinfo.app.java.version=21info.app.type=Spring Bootserver.port=8081eureka.client.register-with-eureka=trueeureka.client.fetch-registry=trueeureka.client.service-url.defaultZone=http://localhost:8761/eureka/eureka.instance.hostname=localhost

従業員サービスの構成は microservices-architecture-mongodb-config-repo/employee-service.propertiesファイルで定義されます。

spring.data.mongodb.uri=${MONGODB_URI_2:mongodb://localhost:27018}spring.threads.virtual.enabled=truemanagement.endpoints.web.exposure.include=*management.info.env.enabled=trueinfo.app.name=Employee Microserviceinfo.app.java.version=21info.app.type=Spring Bootserver.port=8082eureka.client.register-with-eureka=trueeureka.client.fetch-registry=trueeureka.client.service-url.defaultZone=http://localhost:8761/eureka/eureka.instance.hostname=localhost

注意

ローカル開発では、会社サービスはポート 27017 のMongoDBに接続し、従業員サービスはポート 27018 のMongoDBに接続します。本番環境では、個別のMongoDB Atlasクラスターを使用し、MONGODB_URI_1 と MONGODB_URI_2 環境変数を使用して接続文字列を設定します。

7

すべてのサービスを開始した後、次のサービスがを実行中いることを確認して、マイクロサービス アーキテクチャが正しく動作していることを確認します。

  • ポート 8888 のコンフィギュレーションサーバー

  • ポート 8761 のサービス レジストリ

  • ポート 8080 のAPIゲートウェイ

  • ポート 8081 の会社サービス

  • ポート 8082 の従業員サービス

また、ポート 27017 と 27018 で実行中の 2 つのMongoDBインスタンス、または 2 つのMongoDB Atlasクラスターがあることを確認してください。

次のコマンドを実行してテストスクリプトを実行します。

./2_api-tests.sh

スクリプトは会社と従業員を作成し、 REST API を使用してそれらを検索します。スクリプトによって返される出力は次のようになります。

DELETE Companies2DELETE Employees2 POST Company 'MongoDB'POST Company 'Google' GET Company 'MongoDB' by 'id'{ "id": "661aac7904e1bf066ee8e214", "name": "MongoDB", "headquarters": "New York", "created": "2009-02-11T00:00:00.000+00:00"} GET Company 'Google' by 'name'{ "id": "661aac7904e1bf066ee8e216", "name": "Google", "headquarters": "Mountain View", "created": "1998-09-04T00:00:00.000+00:00"} GET Companies[ { "id": "661aac7904e1bf066ee8e214", "name": "MongoDB", "headquarters": "New York", "created": "2009-02-11T00:00:00.000+00:00" }, { "id": "661aac7904e1bf066ee8e216", "name": "Google", "headquarters": "Mountain View", "created": "1998-09-04T00:00:00.000+00:00" }] POST Employee MaximePOST Employee Tim GET Employee 'Maxime' by 'id'{ "id": "661aac79cf04401110c03516", "firstName": "Maxime", "lastName": "Beugnet", "company": "Google", "headquarters": "Mountain View", "created": "1998-09-04T00:00:00.000+00:00", "joined": "2018-02-12T00:00:00.000+00:00", "salary": 2468} GET Employee 'Tim' by 'id'{ "id": "661aac79cf04401110c03518", "firstName": "Tim", "lastName": "Kelly", "company": "MongoDB", "headquarters": "New York", "created": "2009-02-11T00:00:00.000+00:00", "joined": "2023-08-23T00:00:00.000+00:00", "salary": 13579} GET Employees[ { "id": "661aac79cf04401110c03516", "firstName": "Maxime", "lastName": "Beugnet", "company": "Google", "headquarters": "Mountain View", "created": "1998-09-04T00:00:00.000+00:00", "joined": "2018-02-12T00:00:00.000+00:00", "salary": 2468 }, { "id": "661aac79cf04401110c03518", "firstName": "Tim", "lastName": "Kelly", "company": "MongoDB", "headquarters": "New York", "created": "2009-02-11T00:00:00.000+00:00", "joined": "2023-08-23T00:00:00.000+00:00", "salary": 13579 }]

従業員サービスは、会社の詳細を検索するために会社サービスをクエリします。次のコードは、従業員サービスがサービス レジストリを介して会社のサービスと通信する方法を示しています。

private CompanyDTO getCompany(String company) { String url = "http://company-service/api/company/name/"; CompanyDTO companyDTO = restTemplate.getForObject(url + company, CompanyDTO.class); if (companyDTO == null) { throw new EntityNotFoundException("Company not found: ", company); } return companyDTO;}

このURL、 IPアドレスとポートではなく、会社のサービスを名前で参照し、サービス レジストリが正しく機能していることを確認します。

spring とMongoDBを使用してマイクロサービスを構築する方法の詳細については、次のリソースを参照してください。