1概要
Spring Cloudは、堅牢なクラウドアプリケーションを構築するためのフレームワークです。このフレームワークは、分散環境に移行するときに直面する多くの一般的な問題に対する解決策を提供することによって、アプリケーションの開発を容易にします。
マイクロサービスアーキテクチャで動作するアプリケーションは、開発、展開、およびメンテナンスを簡素化することを目的としています。アプリケーションの分解された性質により、開発者は一度に1つの問題に集中することができます。
システムの他の部分に影響を与えずに改善を加えることができます。
一方、マイクロサービスアプローチを採用すると、さまざまな課題が生じます。
-
柔軟化され、必要としないように設定を外部化する
変更時にサービスを再構築 ** サービス発見
-
異なるホストにデプロイされたサービスの複雑さを隠す
この記事では、構成サーバー、ディスカバリー・サーバー、ゲートウェイ・サーバー、ブック・サービス、そして最後に評価サービスという5つのマイクロサービスを構築します。これら5つのマイクロサービスは、クラウド開発を開始し、前述の課題に対処するための強固な基盤アプリケーションを形成します。
2構成サーバー
クラウドアプリケーションを開発する際の1つの問題は、設定を維持して当社のサービスに配布することです。サービスを水平方向に拡張する前に各環境の設定に時間を費やしたり、設定をアプリケーションに組み込むことでセキュリティ侵害の危険性を冒したりすることは、本当に望ましくありません。
これを解決するために、私たちはすべての設定を単一のGitリポジトリに統合し、それを1つのアプリケーションに接続します。非常に単純な実装を設定する予定です。
より詳細を知り、より複雑な例を見るには、 Spring Cloud Configuration の記事を見てください。
2.1. セットアップ
start.spring.io に移動して、Maven and Spring Boot 1.4.xを選択します。
成果物を「 config」 に設定します。依存関係セクションで“ config server” を検索し、そのモジュールを追加します。それから generate ボタンを押すと、事前に設定されたプロジェクトの入ったzipファイルをダウンロードすることができます。
あるいは、 Spring Boot プロジェクトを生成してPOMファイルに依存関係を手動で追加することもできます。
これらの依存関係は、すべてのプロジェクト間で共有されます。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
設定サーバーに依存関係を追加しましょう。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
参考のために:あなたは Maven Central で最新バージョンを見つけることができます。 22春の雲 - 依存関係22%[春の雲 - 依存関係]、https://search.maven.org/classic/#search%7Cgav%7C1%7Cg%3A%22org.springframework.boot%22%20AND%20a% 3A%22spring-boot-start-test-22%[テスト]、https://search.maven.org/classic/#search%7Cgav%7C1%7Cg%3A%22org.springframework.cloud%22%20AND%20a% 3A%22スプリングクラウド設定サーバー%22[設定サーバー])。
2.2. Spring Config
設定サーバーを有効にするには、メインアプリケーションクラスにアノテーションを追加する必要があります。
@SpringBootApplication
@EnableConfigServer
public class ConfigApplication {...}
@ EnableConfigServer はアプリケーションを構成サーバーに変えます。
2.3. プロパティ
src/main/resourcesに application.properties を追加しましょう。
server.port=8081
spring.application.name=config
spring.cloud.config.server.git.uri=file://${user.home}/application-config
設定サーバーの最も重要な設定は git.uri パラメータです。現在、これは相対ファイルパスに設定されており、通常はWindowsでは c:\ Users \\ {username} \ 、** nixでは /Users/\ {username}/ に解決されます。このプロパティは、他のすべてのアプリケーションのプロパティファイルが格納されているGitリポジトリを指します。必要に応じて絶対ファイルパスに設定できます。
-
ヒント :Windowsマシンでは、値の前に 'file:///'を付け、 nixでは 'file://'を使います。
2.4. Gitリポジトリ
spring.cloud.config.server.git.uri で定義されているフォルダに移動し、「application-config」フォルダを追加します。そのフォルダにCDを入力し、 git init と入力します。これでGitリポジトリが初期化され、そこでファイルを保存してその変更を追跡できます。
2.5. 実行
設定サーバーを実行して、動作していることを確認しましょう。コマンドラインから mvn spring-boot:run と入力します。これでサーバーが起動します。サーバーが稼働していることを示すこの出力が表示されます。
Tomcat started on port(s): 8081 (http)
3発見
構成に注意を払ったので、すべてのサーバーがお互いを見つけられるようにする方法が必要です。この問題を解決するには、 Eureka ディスカバリーサーバーを設定します。私たちのアプリケーションはどんなip/portの組み合わせでも動くことができるので、私たちはアプリケーションアドレス検索として役立つことができる中央アドレスレジストリを必要とします。
新しいサーバーがプロビジョニングされると、それはディスカバリーサーバーと通信し、他のユーザーがそれと通信できるようにアドレスを登録します。
このようにして、他のアプリケーションは要求を出すときにこの情報を消費することができます。
詳細を知り、より複雑なディスカバリーの実装を見るには、 Spring Cloud Eurekaの記事 を参照してください。
3.1. セットアップ
再度http://start.spring.io/[start.spring.io]に移動します。アーティファクトを「発見」に設定します。 “ eureka server ”を検索し、その依存関係を追加してください。 “ config client ”を検索し、その依存関係を追加します。
プロジェクトを生成します。
別の方法として、 Spring Boot プロジェクトを作成し、設定サーバーから POM の内容をコピーして、これらの依存関係を交換することもできます。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
参考のために:あなたは Maven Central 上のバンドルを見つけるでしょう-cloud-starter-config%22[設定 - クライアント]、https://search.maven.org/classic/#search%7Cgav%7C1%7Cg%3A%22org.springframework.cloud%22%20AND%20a%3A %22スプリングクラウドスターターユーレカサーバー%22[ユーレカサーバー])。
3.2. Spring Config
メインクラスにJava configを追加しましょう。
@SpringBootApplication
@EnableEurekaServer
public class DiscoveryApplication {...}
@ EnableEurekaServer は、このサーバーを Netflix Eureka を使用して検出サーバーとして構成します。 Spring Boot はクラスパスへの依存関係を自動的に検出し、設定サーバーから設定を検索します。
3.3. プロパティ
それでは、2つのプロパティファイルを追加します。
src/main/resourcesの bootstrap.properties
spring.cloud.config.name=discovery
spring.cloud.config.uri=http://localhost:8081
これらのプロパティにより、ディスカバリサーバは起動時に設定サーバに問い合わせることができます。
Gitリポジトリの discovery.properties
spring.application.name=discovery
server.port=8082
eureka.instance.hostname=localhost
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
ファイル名は spring.application.name プロパティと一致する必要があります。
また、このサーバーはデフォルトゾーンで動作していることを伝えています。これは設定クライアントの地域設定と一致しています。また、サーバーに別の検出インスタンスに登録しないように指示しています。
本番環境では、障害が発生した場合に冗長性を提供するためにこれらのうちの1つ以上があり、その設定は正しいと考えられます。
ファイルをGitリポジトリにコミットしましょう。それ以外の場合、ファイルは検出されません。
3.4. 構成サーバーへの依存関係の追加
この依存関係を設定サーバーのPOMファイルに追加します。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
参考 : バンドルは Maven Central (https://search.maven.org/classic/#search%7Cgav%7C1%7Cg%3A%22org.springframework.cloud%22%20AND%20a)にあります%3A%22スプリングクラウドスターターユーレカ%22[ユーレカクライアント])。
これらのプロパティを、設定サーバーのsrc/main/resourcesにある application.properties ファイルに追加します。
eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/----
==== ** 3.5. 実行**
同じコマンド__mvn spring-boot:run__を使用してディスカバリーサーバーを始動します。コマンドラインからの出力には、次のものが含まれます。
[source,text,gutter:,true]
Fetching config from server at: http://localhost:8081 … Tomcat started on port(s): 8082 (http)
構成サービスを停止して再実行してください。すべてうまくいっていれば、次のようになります。 [source,text,gutter:,true]
DiscoveryClient CONFIG/10.1.10.235:config:8081: registering service… Tomcat started on port(s): 8081 (http) DiscoveryClient CONFIG/10.1.10.235:config:8081 - registration status: 204
=== ** 4ゲートウェイ** 構成と検出に関する問題が解決されたので、クライアントがすべてのアプリケーションにアクセスするという問題が依然としてあります。 分散システムにすべてを残すと、クライアントでクロスオリジン要求を許可するために複雑なCORSヘッダーを管理する必要があります。 これを解決するには、__Gateway__サーバーを作成します。これは、クライアントからバックエンドサーバーへのリクエストを往復させるリバースプロキシとして機能します。 ゲートウェイサーバーは、すべての応答を単一のホストから発信できるため、マイクロサービスアーキテクチャにおける優れたアプリケーションです。 これにより、CORSが不要になり、認証などの一般的な問題を処理するのに便利な場所になります。 ==== ** 4.1. セットアップ** 今ではドリルを知っています。 http://start.spring.io/[start.spring.io]に移動します。アーティファクトを「__ゲートウェイ__」に設定します。 “ zuul”を検索し、その依存関係を追加してください。 “ __config client” __を検索し、その依存関係を追加します。 “ __eureka discovery” __を検索し、その依存関係を追加してください。そのプロジェクトを生成します。 あるいは、これらの依存関係を持つ__Spring Boot__アプリを作成することもできます。 [source,xml,gutter:,true]
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency>
参考のために:あなたは__Maven Central__上のバンドルを見つけるでしょう-cloud-starter-config%22[設定 - クライアント]、https://search.maven.org/classic/#search%7Cgav%7C1%7Cg%3A%22org.springframework.cloud%22%20AND%20a%3A %22spring-cloud-starter-eureka%22[eureka-client]、https://search.maven.org/classic/#search%7C1%7Cg%3A%22org.springframework.cloud%22%20AND%20a %3A%22スプリングクラウドスターターズール%22[ズール])。 ==== ** 4.2. Spring Config ** メインクラスに設定を追加しましょう: [source,java,gutter:,true]
@SpringBootApplication @EnableZuulProxy @EnableEurekaClient public class GatewayApplication {…}
==== ** 4.3. プロパティ** それでは、2つのプロパティファイルを追加します。 src/main/resourcesの__bootstrap.properties__ [source,text,gutter:,true]
spring.cloud.config.name=gateway spring.cloud.config.discovery.service-id=config spring.cloud.config.discovery.enabled=true
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/----
Gitリポジトリのgateway.properties
spring.application.name=gateway
server.port=8080
eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5
zuul.routes.book-service.path=/book-service/** **
zuul.routes.book-service.sensitive-headers=Set-Cookie,Authorization
hystrix.command.book-service.execution.isolation.thread.timeoutInMilliseconds=600000
zuul.routes.rating-service.path=/rating-service/** **
zuul.routes.rating-service.sensitive-headers=Set-Cookie,Authorization
hystrix.command.rating-service.execution.isolation.thread.timeoutInMilliseconds=600000
zuul.routes.discovery.path=/discovery/** **
zuul.routes.discovery.sensitive-headers=Set-Cookie,Authorization
zuul.routes.discovery.url=http://localhost:8082
hystrix.command.discovery.execution.isolation.thread.timeoutInMilliseconds=600000
zuul.routes プロパティを使用すると、ant URL matcherに基づいて特定のリクエストをルーティングするためのアプリケーションを定義できます。私たちの財産は Zuul に、/book-service/ に入ってくるすべてのリクエストをbook-serviceの spring.application.name を持つアプリケーションにルーティングするように伝えます。 Zuul は、アプリケーション名を使用してディスカバリーサーバーからホストを検索し、そのサーバーに要求を転送します。
リポジトリの変更をコミットするのを忘れないでください。
4.4. 実行
設定アプリケーションと検出アプリケーションを実行し、設定アプリケーションが検出サーバーに登録されるまで待ちます。それらがすでに実行されている場合は、それらを再起動する必要はありません。それが完了したら、ゲートウェイサーバを実行して下さい。ゲートウェイサーバーはポート8080で起動し、検出サーバーに登録する必要があります。コンソールからの出力には、次のものが含まれます。
Fetching config from server at: http://10.1.10.235:8081/...
DiscoveryClient__GATEWAY/10.1.10.235:gateway:8080: registering service...
DiscoveryClient__GATEWAY/10.1.10.235:gateway:8080 - registration status: 204
Tomcat started on port(s): 8080 (http)
簡単な間違いの1つは、config serverが Eureka に登録される前にサーバーを起動することです。この場合、この出力とのログを見ます:
Fetching config from server at: http://localhost:8888
これは設定サーバのデフォルトのURLとポートで、設定要求が行われたときにディスカバリサービスがアドレスを持っていなかったことを示します。設定サーバーがEurekaに登録されたら、数秒待ってからもう一度お試しください。問題は解決します。
5ブックサービス
マイクロサービスアーキテクチャでは、ビジネスの目的に合わせて自由にアプリケーションを作成できます。多くの場合、エンジニアはドメインごとにサービスを分割します。このパターンに従って、アプリケーション内の書籍に対するすべての操作を処理するための書籍サービスを作成します。
5.1. セットアップ
もう1回。 start.spring.io に移動します。アーティファクトを「ブックサービス」に設定します。 “ web ”を検索し、その依存関係を追加してください。 “ config client ”を検索し、その依存関係を追加します。 “ eureka discovery” を検索し、その依存関係を追加してください。そのプロジェクトを生成します。
あるいは、これらの依存関係をプロジェクトに追加します。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
参考のために:あなたは Maven Central (https://search.maven.org/classic/#search%7Cgav%7C1%7Cg%3A%22org.springframework.cloud%22%20AND%20a%3A%22springにバンドルを見つけるでしょう-cloud-starter-config%22[設定 - クライアント]、https://search.maven.org/classic/#search%7Cgav%7C1%7Cg%3A%22org.springframework.cloud%22%20AND%20a%3A %22spring-cloud-starter-eureka%22[eureka-client]、https://search.maven.org/classic/#search%7C1%7Cg%3A%22org.springframework.boot%22%20AND%20a %3A%22スプリングブートスターターウェブ%22[ウェブ])。
5.2. Spring Config
メインクラスを修正しましょう。
@SpringBootApplication
@EnableEurekaClient
@RestController
@RequestMapping("/books")
public class BookServiceApplication {
public static void main(String[]args) {
SpringApplication.run(BookServiceApplication.class, args);
}
private List<Book> bookList = Arrays.asList(
new Book(1L, "Baeldung goes to the market", "Tim Schimandle"),
new Book(2L, "Baeldung goes to the park", "Slavisa")
);
@GetMapping("")
public List<Book> findAllBooks() {
return bookList;
}
@GetMapping("/{bookId}")
public Book findBook(@PathVariable Long bookId) {
return bookList.stream().filter(b -> b.getId().equals(bookId)).findFirst().orElse(null);
}
}
また、設定時に設定する値を返すために、RESTコントローラと、プロパティファイルで設定されたフィールドを追加しました。
それでは、POJOという本を追加しましょう。
public class Book {
private Long id;
private String author;
private String title;
//standard getters and setters
}
5.3. プロパティ
2つのプロパティファイルを追加するだけです。
src/main/resourcesの bootstrap.properties :
spring.cloud.config.name=book-service
spring.cloud.config.discovery.service-id=config
spring.cloud.config.discovery.enabled=true
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/----
Gitリポジトリの__book-service.properties__:
[source,text,gutter:,true]
spring.application.name=book-service server.port=8083
eureka.client.region = default eureka.client.registryFetchIntervalSeconds = 5 eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/----
変更をリポジトリにコミットしましょう。
5.4. 実行
他のすべてのアプリケーションが起動したら、ブックサービスを開始できます。コンソールの出力は次のようになります。
DiscoveryClient__BOOK-SERVICE/10.1.10.235:book-service:8083: registering service...
DiscoveryClient__BOOK-SERVICE/10.1.10.235:book-service:8083 - registration status: 204
Tomcat started on port(s): 8083 (http)
起動したら、ブラウザを使用して、作成したばかりのエンドポイントにアクセスできます。 http://localhost:8080/book-service/booksに移動すると、outコントローラに追加した2冊の本を含むJSONオブジェクトが返されます。ブックサービスにポート8083で直接アクセスしているのではなく、ゲートウェイサーバーを経由していることに注意してください。
6. 評価サービス
私たちのブックサービスと同様に、私たちの格付けサービスは、格付けに関連する操作を処理するドメイン主導のサービスになります。
6.1. セットアップ
もう1回。 start.spring.io に移動します。成果物を「rating-service」に設定します。 “ web ”を検索し、その依存関係を追加してください。 “ config client ”を検索し、その依存関係を追加します。 “ eureka discovery” を検索し、その依存関係を追加してください。そのプロジェクトを生成します。
あるいは、これらの依存関係をプロジェクトに追加します。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
参考のために:あなたは Maven Central (https://search.maven.org/classic/#search%7Cgav%7C1%7Cg%3A%22org.springframework.cloud%22%20AND%20a%3A%22springにバンドルを見つけるでしょう-cloud-starter-config%22[設定 - クライアント]、https://search.maven.org/classic/#search%7Cgav%7C1%7Cg%3A%22org.springframework.cloud%22%20AND%20a%3A %22spring-cloud-starter-eureka%22[eureka-client]、https://search.maven.org/classic/#search%7C1%7Cg%3A%22org.springframework.boot%22%20AND%20a %3A%22スプリングブートスターターウェブ%22[ウェブ])。
6.2. Spring Config
メインクラスを修正しましょう。
@SpringBootApplication
@EnableEurekaClient
@RestController
@RequestMapping("/ratings")
public class RatingServiceApplication {
public static void main(String[]args) {
SpringApplication.run(RatingServiceApplication.class, args);
}
private List<Rating> ratingList = Arrays.asList(
new Rating(1L, 1L, 2),
new Rating(2L, 1L, 3),
new Rating(3L, 2L, 4),
new Rating(4L, 2L, 5)
);
@GetMapping("")
public List<Rating> findRatingsByBookId(@RequestParam Long bookId) {
return bookId == null || bookId.equals(0L) ? Collections.EMPTY__LIST : ratingList.stream().filter(r -> r.getBookId().equals(bookId)).collect(Collectors.toList());
}
@GetMapping("/all")
public List<Rating> findAllRatings() {
return ratingList;
}
}
また、設定時に設定する値を返すために、RESTコントローラと、プロパティファイルで設定されたフィールドを追加しました。
評価POJOを追加しましょう。
public class Rating {
private Long id;
private Long bookId;
private int stars;
//standard getters and setters
}
6.3. プロパティ
2つのプロパティファイルを追加するだけです。
src/main/resourcesの bootstrap.properties :
spring.cloud.config.name=rating-service
spring.cloud.config.discovery.service-id=config
spring.cloud.config.discovery.enabled=true
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/----
Gitリポジトリの__rating-service.properties__:
[source,text,gutter:,true]
spring.application.name=rating-service server.port=8084
eureka.client.region = default eureka.client.registryFetchIntervalSeconds = 5 eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/----
変更をリポジトリにコミットしましょう。
6.4. 実行
他のすべてのアプリケーションが起動したら、評価サービスを開始できます。コンソールの出力は次のようになります。
DiscoveryClient__RATING-SERVICE/10.1.10.235:rating-service:8083: registering service...
DiscoveryClient__RATING-SERVICE/10.1.10.235:rating-service:8083 - registration status: 204
Tomcat started on port(s): 8084 (http)
起動したら、ブラウザを使用して、作成したばかりのエンドポイントにアクセスできます。 http://localhost:8080/rating-service/ratings/allに移動すると、すべての評価を含むJSONが返されます。ポート8084で直接評価サービスにアクセスしているのではなく、ゲートウェイサーバーを経由していることに注意してください。
7. 結論
これで Spring Cloud のさまざまな部分を機能するマイクロサービスアプリケーションに接続できます。これは、より複雑なアプリケーションの構築を始めるために使用できる基盤を形成します。
いつものように、このソースコードはhttps://github.com/eugenp/tutorials/tree/master/spring-cloud/spring-cloud-bootstrap[Github]にあります。