Google Code Prettify

2021年2月18日 星期四

Spring Cloud Gateway: getting started

Spring Cloud 在 2020 年用 Gateway 取代原本的網關 Zuul,新的網關 Gateway 功能更強,效率更高,對 developer 來說,使用上是一樣的簡單。


如上圖是我的環境,我的所有服務放在一台 CentOS 7 上的 Docker 裡,Docker 上有服務註冊的 consul,有提供服務的 wealth-system,這個服務當輸入 http://192.168.50.13:8080/customer/E243350588 會傳回客戶的基本資料。現在要來看 gateway 怎麼寫 …

** 建立一個 spring boot 專案 **

         在 build.gradle 的 dependencies 中加入以下內容,以導入所需要的 jar 檔。

  1. implementation 'org.springframework.cloud:spring-cloud-starter-consul-discovery'
  2. implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
  3. implementation 'org.springframework.boot:spring-boot-starter-actuator'

  • 第 1 行是 consul 註冊、查詢服務所需要的 jar 檔
  • 第 2 行是導入新版 gateway
  • 第 3 行是 health check 所需要的 jar 檔

  1. server:
  2. servlet:
  3. context-path: /
  4. port: 80
  5. management:
  6. server:
  7. base-path: /
  8. port: 5001
  9. endpoint:
  10. health:
  11. probes:
  12. enabled: true
  13. show-details: always
  14. spring:
  15. application:
  16. name: fstop-gateway
  17. profiles:
  18. active: ${SPRING_PROFILES_ACTIVE}
  19. main:
  20. banner-mode: off
  21. cloud:
  22. consul:
  23. enabled: true
  24. host: 192.168.50.13
  25. port: 8500
  26. discovery:
  27. prefer-ip-address: true
  28. instance-id: ${spring.application.name}:${random.value}
  29. register-health-check: true
  30. health-check-path: /actuator/health
  31. health-check-interval: 30s
  32. tags: ${spring.application.name}
  33. gateway:
  34. routes:
  35. - id: wealth
  36. uri: lb://wealth-system
  37. predicates:
  38. - Path=/customer/**

上面是 application.yml 的內容,說明如下:

  • 第 24~34 行,將 gateway 註冊到 consul,如果不註冊到 consul,就無法使用 consul 的服務查詢功能。
  • 第 35~40 行是 gateway 的設定,第 37 行只是個標識 (命名),取個有意義的名稱即可,第 38 行指出,當網址有 /customer/** 時,導向 wealth-system 這個服務。特別注意,這裡寫的是 lb://wealth-system (lb: load balance),就是要使用 consul 提供的服務發現的方式導向,也可以寫成 http://192.168.50.8080,這樣就是直接導向服務所在的網址。

沒有留言:

張貼留言