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 檔。
- implementation 'org.springframework.cloud:spring-cloud-starter-consul-discovery'
- implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
- implementation 'org.springframework.boot:spring-boot-starter-actuator'
- 第 1 行是 consul 註冊、查詢服務所需要的 jar 檔
- 第 2 行是導入新版 gateway
- 第 3 行是 health check 所需要的 jar 檔
- server:
- servlet:
- context-path: /
- port: 80
- management:
- server:
- base-path: /
- port: 5001
- endpoint:
- health:
- probes:
- enabled: true
- show-details: always
- spring:
- application:
- name: fstop-gateway
- profiles:
- active: ${SPRING_PROFILES_ACTIVE}
- main:
- banner-mode: off
- cloud:
- consul:
- enabled: true
- host: 192.168.50.13
- port: 8500
- discovery:
- prefer-ip-address: true
- instance-id: ${spring.application.name}:${random.value}
- register-health-check: true
- health-check-path: /actuator/health
- health-check-interval: 30s
- tags: ${spring.application.name}
- gateway:
- routes:
- - id: wealth
- uri: lb://wealth-system
- predicates:
- - 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,這樣就是直接導向服務所在的網址。
沒有留言:
張貼留言