SlideShare a Scribd company logo
1 of 36
JSUG勉強会 2020 その3
Spring Cloud Gateway
on
Kubernetes
2020.4.8 タグバンガーズ 小川
小川岳史
株式会社タグバンガーズ @横浜
Spring ♥️
JSUG スタッフやってます
Microservice はじめました
About
2
本セッションのサンプルコード
3
https://github.com/ogawa-takeshi/spring-cloud-gateway-sample
API Gateway Pattern
クライアントの分離
5
API Gateway
API
API
API
注文
商品
在庫
API
API
API
注文
商品
在庫
クライアントをマイクロサービスの複雑さから分離
API Gateway PatternClient と Microservice のやりとりが直接的
Client Client
マイクロサービスにすると機能ごとにサービスが分割
されエンドポイントがたくさんできる
横断的関心事の軽減
6
商品 API
在庫 API
認証・認可
サービスディスカバリ
Client
サーキットブレーカー
レート制限
ログ記録
IP制限
キャッシュ
認証・認可
サーキットブレーカー
IP制限
キャッシュ
ログ記録
商品 API
在庫 API
注文 API
認証・認可
認証・認可
サーキットブレーカー
レート制限
注文 API
個々のマイクロサービスからゲートウェイに機能をオフ
ロードできる
Client
Spring Cloud Gateway
Spring Cloud Gateway の基礎
3つの構成要素
8
Route:どのサービスにルーティングするかの定義
• 複数の Predicate と Filter を持てる
Predicate
• PathRoutePredicateFactory(パスが xx だったら)
• HeaderRoutePredicateFactory(ヘッダーが xx だったら)
• BetweenRoutePredicateFactory(何時から何時だったら)
→ 特定の時間にメンテナンス画面を出力するなど
• …
Filter
• RewritePathGatewayFilterFactory
• RequestRateLimiterGatewayFilterFactory
• SpringCloudCircuitBreakerFilterFactory
• …
Spring Cloud Gateway はシンプル
WebFlux & Reactor でノンブロッキングに作られている
→ Reactive の知識が必要
はじめかた
9
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
Spring Boot アプリケーションの pom.xml に
Spring Cloud Gateway の Starter を追加するだけ!
pom.xml
Route の設定例
10
Spring Cloud
Gateway
spring:
gateway:
routes:
- id: service-a
uri: http://localhost:8081
predicates:
- Path=/a/**
filters:
- RewritePath=/a(?<segment>/?.*), ${segment}
- id: service-b
uri: http://localhost:8082
predicates:
- Path=/b/**
filters:- RewritePath=/b(?<segment>/?.*), ${segment}
/a/hello
/b/hello
Client
A
Service
Service
B
http://localhost:8081/hello
http://localhost:8082/hello
application.yml
Spring Cloud Gateway
on
Kubernetes
Security Service
Service
12
Client
Monitoring
Distributed
Configuration
Spring エコシステムとの連携
New Service
NEW
B
A
Monitoring
API
Gateway
IdP
Config
Security
Kubernetes
Keycloak
Service A
Service B
GrafanaPrometheus
Spring Cloud
Gateway
Spring Security
Resillience4J
13
Client
Monitoring
Config
アーキテクチャ
New Service
Config
Map
API
Server
Service Discovery
Spring Cloud
Kubernetes
Service Discovery
15
Spring Cloud Kubernetes (Discovery Client)
Service
Service
Service
Spring Cloud
Gateway
A
B
New
Client
Service List
API
Server
Spring Cloud
Kubernetes
Kubernetes
デフォルトのルーティングルール
16
/a/hello
↑Service ID
Service
A
Spring Cloud
Gateway
/hello
Client
spring:
cloud:
gateway:
discovery:
locator:
enabled: true
url-expression: "'http://'+serviceId"
apiVersion: v1
kind: Service
metadata:
labels:
app: service-a
service: "true"
name: a
application.yml manifest.yml
17
ルーティング対象 Service のフィルター
Service
Service
New Service
Spring Cloud
Gateway
A
B
C
Client
Service List
API
Server
D
ラベルがないので
サービスリストに
追加されない
✖️
Label
Label
Label
Kubernetes
18
Spring Cloud Kubernetes (Discovery Client)
Service
Spring Cloud
Gateway
Client
spring:
cloud:
kubernetes:
discovery:
filter: "metadata.labels['service']"
application.yml
apiVersion: v1
kind: Service
metadata:
labels:
app: service-a
service: "true"
name: a
manifest.yml
service:”true”
Service Account
19
Spring Cloud
Gateway
アクセス許可
Kubernetes
manifest.yml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: spring-cloud-kubernetes
rules:
- apiGroups: ["", "extensions", "apps"]
resources: ["configmaps", "pods", "services",
"endpoints", "secrets"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: spring-cloud-kubernetes-binding
subjects:
- kind: ServiceAccount
name: sample
apiGroup: ""
roleRef:
kind: Role
name: spring-cloud-kubernetes
apiGroup: ""
@EnableScheduling
20
@SpringBootApplication
@EnableScheduling
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
@EnableScheduling を設定しないとサービスリストが更新されない
Distributed Configuration
Spring Cloud Kubernetes (Config)
22
Spring Cloud
Gateway
②自動でリロード
Config
Map
application.yml
①Config Mapの変更
Kubernetes
bootstrap.yml
23
application.yml
name: gateway
ConfigMap
spring:
cloud:
kubernetes:
reload:
enabled: true
config:
sources:
- name: gateway
Spring Cloud
Gateway
bootstrap.yml
bootstrap.yml
Circuit Breaker
Resillience4J
25
Service
A
Spring Cloud
Gateway
Service
B
×
<
fallback
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4j</artifactId>
</dependency>
spring:
cloud:
default-filters:
- name: CircuitBreaker
args:
fallbackUri: forward:/fallback
application.yml
pom.xml
Client
Security
27
Service
A
Spring Cloud
Gateway
Service
B
<
JWT
Keycloak
ID/PW
認証
リソース
オーナー
OAuth
クライアント
リソース
サーバ
リソース
サーバ
JWT
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
spring:
security:
oauth2:
client:
provider:
keycloak:
issuer-uri:http://keycloak.sample.test/auth/realms/sample
registration:
keycloak:
client-id: sample
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
pom.xml
Spring Security (OpenID Connect)
IdP
Session
application.yml
TokenRelay
28
spring:
cloud:
gateway:
default-filters:
- TokenRelay=
- RemoveRequestHeader=Cookie
Service
Spring Cloud
Gateway
Client
JWT
Add automatic token refresh to TokenRelayGatewayFilterFactory #175
application.yml
処理フロー
29
Service
①
②Redirect
Session start
③
JWT
session
⑧code
⇅
Token
Keycloak
12 JWT Signature
13 scope
id
JWT11
Spring Cloud
Gateway
⑦Redirect(code)
⑩Login OK
⑨token=JWT
Bearer
Scope による権限制御
30
Service
A
Service
B
Service
C
Anyone
Login
Login
scope: hello
Spring Cloud
Gateway
ログイン権限のみ
ログイン +
hello 権限あり
Cにアクセス
Scope による権限制御
31
@Configuration
public class SecurityConfig {
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http.authorizeExchange()
.matchers(EndpointRequest.toAnyEndpoint()).permitAll()
.pathMatchers("/a/**").permitAll()
.pathMatchers("/c/**").hasAuthority("SCOPE_hello")
.anyExchange().authenticated();
http.oauth2Login();
http.oauth2Client();
http.logout();
http.cors();
return http.build();
}
}
Monitoring
33
Prometheus
Service
A
Spring Cloud
Gateway
Service
B
GrafanaPrometheus
<
Actuator
Micrometer
Client
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
scrape_configs:
-job_name: 'gateway’
metrics_path: /actuator/prometheus
static_configs:
- targets:
- gateway:80
prometheus.yml
pom.xml
34
Grafana
• routeId
• routeUri
• outcome
• status
• httpStatusCode
• httpMethod
まとめ
• Spring Cloud Gateway を導入することで、クライアントからみると一見モノリスでも実はマ
イクロサービスという構成が作れる
• Spring Cloud Kubernetes と組み合わせることで、Discovery Server や Config Server を
用意せずに Kubernetes の機能を活用できる
• Spring Security と組み合わせることでサービスをステートレスな API にできる
まとめ
36

More Related Content

What's hot

OpenID ConnectとSCIMの標準化動向
OpenID ConnectとSCIMの標準化動向OpenID ConnectとSCIMの標準化動向
OpenID ConnectとSCIMの標準化動向
Tatsuo Kudo
 

What's hot (20)

3分でわかるAzureでのService Principal
3分でわかるAzureでのService Principal3分でわかるAzureでのService Principal
3分でわかるAzureでのService Principal
 
ログ管理のベストプラクティス
ログ管理のベストプラクティスログ管理のベストプラクティス
ログ管理のベストプラクティス
 
Kongの概要と導入事例
Kongの概要と導入事例Kongの概要と導入事例
Kongの概要と導入事例
 
Azure Monitor Logで実現するモダンな管理手法
Azure Monitor Logで実現するモダンな管理手法Azure Monitor Logで実現するモダンな管理手法
Azure Monitor Logで実現するモダンな管理手法
 
え、まって。その並列分散処理、Kafkaのしくみでもできるの? Apache Kafkaの機能を利用した大規模ストリームデータの並列分散処理
え、まって。その並列分散処理、Kafkaのしくみでもできるの? Apache Kafkaの機能を利用した大規模ストリームデータの並列分散処理え、まって。その並列分散処理、Kafkaのしくみでもできるの? Apache Kafkaの機能を利用した大規模ストリームデータの並列分散処理
え、まって。その並列分散処理、Kafkaのしくみでもできるの? Apache Kafkaの機能を利用した大規模ストリームデータの並列分散処理
 
IAM Roles Anywhereのない世界とある世界(2022年のAWSアップデートを振り返ろう ~Season 4~ 発表資料)
IAM Roles Anywhereのない世界とある世界(2022年のAWSアップデートを振り返ろう ~Season 4~ 発表資料)IAM Roles Anywhereのない世界とある世界(2022年のAWSアップデートを振り返ろう ~Season 4~ 発表資料)
IAM Roles Anywhereのない世界とある世界(2022年のAWSアップデートを振り返ろう ~Season 4~ 発表資料)
 
AWSのログ管理ベストプラクティス
AWSのログ管理ベストプラクティスAWSのログ管理ベストプラクティス
AWSのログ管理ベストプラクティス
 
モノリスからマイクロサービスへの移行 ~ストラングラーパターンの検証~(Spring Fest 2020講演資料)
モノリスからマイクロサービスへの移行 ~ストラングラーパターンの検証~(Spring Fest 2020講演資料)モノリスからマイクロサービスへの移行 ~ストラングラーパターンの検証~(Spring Fest 2020講演資料)
モノリスからマイクロサービスへの移行 ~ストラングラーパターンの検証~(Spring Fest 2020講演資料)
 
Tech Summit 2018 【事例紹介】 自社サービスに Azure IoT Hub Device Provisioning Serviceを適用してみた
Tech Summit 2018 【事例紹介】 自社サービスに Azure IoT Hub Device Provisioning Serviceを適用してみたTech Summit 2018 【事例紹介】 自社サービスに Azure IoT Hub Device Provisioning Serviceを適用してみた
Tech Summit 2018 【事例紹介】 自社サービスに Azure IoT Hub Device Provisioning Serviceを適用してみた
 
JIRA / Confluence の 必須プラグインはこれだ
JIRA / Confluence の必須プラグインはこれだJIRA / Confluence の必須プラグインはこれだ
JIRA / Confluence の 必須プラグインはこれだ
 
Multicastが出来ないならUnicastすればいいじゃない
Multicastが出来ないならUnicastすればいいじゃないMulticastが出来ないならUnicastすればいいじゃない
Multicastが出来ないならUnicastすればいいじゃない
 
Keycloakの実際・翻訳プロジェクト紹介
Keycloakの実際・翻訳プロジェクト紹介Keycloakの実際・翻訳プロジェクト紹介
Keycloakの実際・翻訳プロジェクト紹介
 
KeycloakのDevice Flow、CIBAについて
KeycloakのDevice Flow、CIBAについてKeycloakのDevice Flow、CIBAについて
KeycloakのDevice Flow、CIBAについて
 
設計・構築においてのドキュメントの重要性について
設計・構築においてのドキュメントの重要性について設計・構築においてのドキュメントの重要性について
設計・構築においてのドキュメントの重要性について
 
OpenID ConnectとSCIMの標準化動向
OpenID ConnectとSCIMの標準化動向OpenID ConnectとSCIMの標準化動向
OpenID ConnectとSCIMの標準化動向
 
Data platformdesign
Data platformdesignData platformdesign
Data platformdesign
 
PostgreSQLをKubernetes上で活用するためのOperator紹介!(Cloud Native Database Meetup #3 発表資料)
PostgreSQLをKubernetes上で活用するためのOperator紹介!(Cloud Native Database Meetup #3 発表資料)PostgreSQLをKubernetes上で活用するためのOperator紹介!(Cloud Native Database Meetup #3 発表資料)
PostgreSQLをKubernetes上で活用するためのOperator紹介!(Cloud Native Database Meetup #3 発表資料)
 
Keycloak入門
Keycloak入門Keycloak入門
Keycloak入門
 
Cisco Modeling Labs (CML)を使ってネットワークを学ぼう!(基礎編)配布用
Cisco Modeling Labs (CML)を使ってネットワークを学ぼう!(基礎編)配布用Cisco Modeling Labs (CML)を使ってネットワークを学ぼう!(基礎編)配布用
Cisco Modeling Labs (CML)を使ってネットワークを学ぼう!(基礎編)配布用
 
基礎からのOAuth 2.0とSpring Security 5.1による実装
基礎からのOAuth 2.0とSpring Security 5.1による実装基礎からのOAuth 2.0とSpring Security 5.1による実装
基礎からのOAuth 2.0とSpring Security 5.1による実装
 

Similar to Spring Cloud Gateway on Kubernetes

Single SignOn Product "Gatekeeper"
Single SignOn Product "Gatekeeper"Single SignOn Product "Gatekeeper"
Single SignOn Product "Gatekeeper"
GOLDandLAPIS
 

Similar to Spring Cloud Gateway on Kubernetes (20)

Azureをフル活用したサーバーレスの潮流について
Azureをフル活用したサーバーレスの潮流についてAzureをフル活用したサーバーレスの潮流について
Azureをフル活用したサーバーレスの潮流について
 
Design Pattern MicroServices Architecture in Japanese
Design Pattern MicroServices Architecture in JapaneseDesign Pattern MicroServices Architecture in Japanese
Design Pattern MicroServices Architecture in Japanese
 
Sum awsloft tko-iotloft-10-lt4-may-2020
Sum awsloft tko-iotloft-10-lt4-may-2020Sum awsloft tko-iotloft-10-lt4-may-2020
Sum awsloft tko-iotloft-10-lt4-may-2020
 
20200630 AWS Black Belt Online Seminar Amazon Cognito
20200630 AWS Black Belt Online Seminar Amazon Cognito20200630 AWS Black Belt Online Seminar Amazon Cognito
20200630 AWS Black Belt Online Seminar Amazon Cognito
 
20190731 Azure Functions x Line at Azure Tech Lab #4
20190731 Azure Functions x Line at Azure Tech Lab #420190731 Azure Functions x Line at Azure Tech Lab #4
20190731 Azure Functions x Line at Azure Tech Lab #4
 
Kubernete Gateway APIとAmazon VPC Lattice.pptx
Kubernete Gateway APIとAmazon VPC Lattice.pptxKubernete Gateway APIとAmazon VPC Lattice.pptx
Kubernete Gateway APIとAmazon VPC Lattice.pptx
 
Kong meetup tokyo 2018.10.26 ブリスコラ
Kong meetup tokyo 2018.10.26 ブリスコラKong meetup tokyo 2018.10.26 ブリスコラ
Kong meetup tokyo 2018.10.26 ブリスコラ
 
Keycloakのステップアップ認証について
Keycloakのステップアップ認証についてKeycloakのステップアップ認証について
Keycloakのステップアップ認証について
 
Single SignOn Product "Gatekeeper"
Single SignOn Product "Gatekeeper"Single SignOn Product "Gatekeeper"
Single SignOn Product "Gatekeeper"
 
[AC11] サーバー管理よ、サヨウナラ。サーバーレスアーキテクチャの意義と実践
[AC11] サーバー管理よ、サヨウナラ。サーバーレスアーキテクチャの意義と実践[AC11] サーバー管理よ、サヨウナラ。サーバーレスアーキテクチャの意義と実践
[AC11] サーバー管理よ、サヨウナラ。サーバーレスアーキテクチャの意義と実践
 
AWS Black Belt Online Seminar AWS Amplify
AWS Black Belt Online Seminar AWS AmplifyAWS Black Belt Online Seminar AWS Amplify
AWS Black Belt Online Seminar AWS Amplify
 
Build ハイライト アップデート
Build ハイライト アップデートBuild ハイライト アップデート
Build ハイライト アップデート
 
Keycloakの最近のトピック
Keycloakの最近のトピックKeycloakの最近のトピック
Keycloakの最近のトピック
 
Web サーバー管理者のための Azure App Service 再入門
Web サーバー管理者のための Azure App Service 再入門Web サーバー管理者のための Azure App Service 再入門
Web サーバー管理者のための Azure App Service 再入門
 
Amazon FreeRTOSを用いた量産向けIoTマイコンデバイス開発プロトタイピング
Amazon FreeRTOSを用いた量産向けIoTマイコンデバイス開発プロトタイピングAmazon FreeRTOSを用いた量産向けIoTマイコンデバイス開発プロトタイピング
Amazon FreeRTOSを用いた量産向けIoTマイコンデバイス開発プロトタイピング
 
英国オープンバンキング技術仕様の概要
英国オープンバンキング技術仕様の概要英国オープンバンキング技術仕様の概要
英国オープンバンキング技術仕様の概要
 
[AC07] 米国マイクロソフト本社で体験したノウハウを伝授!マイクロサービス実行基盤Azure Service Fabricの勘所
[AC07] 米国マイクロソフト本社で体験したノウハウを伝授!マイクロサービス実行基盤Azure Service Fabricの勘所[AC07] 米国マイクロソフト本社で体験したノウハウを伝授!マイクロサービス実行基盤Azure Service Fabricの勘所
[AC07] 米国マイクロソフト本社で体験したノウハウを伝授!マイクロサービス実行基盤Azure Service Fabricの勘所
 
[de:code 2018] [AD35] オープンソースのマイクロサービス/コンテナー プラットフォーム「Azure Service Fabric」の使...
[de:code 2018] [AD35] オープンソースのマイクロサービス/コンテナー プラットフォーム「Azure Service Fabric」の使...[de:code 2018] [AD35] オープンソースのマイクロサービス/コンテナー プラットフォーム「Azure Service Fabric」の使...
[de:code 2018] [AD35] オープンソースのマイクロサービス/コンテナー プラットフォーム「Azure Service Fabric」の使...
 
Cloud で Active Directory を活用するには
Cloud で Active Directory を活用するにはCloud で Active Directory を活用するには
Cloud で Active Directory を活用するには
 
Kubernetes Service Account As Multi-Cloud Identity / Cloud Native Security Co...
Kubernetes Service Account As Multi-Cloud Identity / Cloud Native Security Co...Kubernetes Service Account As Multi-Cloud Identity / Cloud Native Security Co...
Kubernetes Service Account As Multi-Cloud Identity / Cloud Native Security Co...
 

More from Takeshi Ogawa (6)

今こそ知りたい Spring Data
今こそ知りたい Spring Data今こそ知りたい Spring Data
今こそ知りたい Spring Data
 
Spring I/O 2019 Recap - Moduliths
Spring I/O 2019 Recap - ModulithsSpring I/O 2019 Recap - Moduliths
Spring I/O 2019 Recap - Moduliths
 
Spring data-rest-and-spring-cloud-contract
Spring data-rest-and-spring-cloud-contractSpring data-rest-and-spring-cloud-contract
Spring data-rest-and-spring-cloud-contract
 
さくっと作るSpring入門 with Google Home
さくっと作るSpring入門 with Google Homeさくっと作るSpring入門 with Google Home
さくっと作るSpring入門 with Google Home
 
Spring と TDD
Spring と TDDSpring と TDD
Spring と TDD
 
さくっと理解するSpring bootの仕組み
さくっと理解するSpring bootの仕組みさくっと理解するSpring bootの仕組み
さくっと理解するSpring bootの仕組み
 

Spring Cloud Gateway on Kubernetes

Editor's Notes

  1. 今回のテーマは without Netflix OSS Zuul の後継である Spring Cloud Gateway
  2. Microservice は最近はじめた Spring Cloud Gateway を使う機会があったのでナレッジ共有
  3. Spring Cloud Gateway は一言でいえばマイクロサービスのデザインパターンとして知られる API Gateway パターンを Spring Boot ベースで実装できるライブラリ
  4. マイクロサービスにすると機能ごとにサービスが分割され、 エンドポイントがたくさんできる クライアントは複数のエンドポイントを気にしなければいけない マイクロサービスのエッジに API Gateway を置くことで、クライアントのマイクロサービスの複雑さから隔離できる
  5. 共通でやりたいことを各サービスで重複して実装しなければならい
  6. Spring Cloud Gateway はシンプル 3つの構成要素
  7. Java ベースの設定も可能
  8. Kubernetes 上で Spring Cloud Gateway を ... を紹介するよ! 他の Spring エコシステムとの組み合わせでいろんなことができる!
  9. Service Discovery Distributed Cofiguration
  10. Service を自動検知するので、個別の Route の設定が必要ない
  11. リソースサーバはステートレスな作りにできる!