1. 程式人生 > 程式設計 >Spring Cloud Gateway 註冊到服務中心 Consul,代理服務中心的所有服務

Spring Cloud Gateway 註冊到服務中心 Consul,代理服務中心的所有服務

閘道器 Gateway 註冊到服務中心 Consul

Spring Cloud Gateway 提供了一種預設轉發的能力,只要將 Spring Cloud Gateway 註冊到服務中心,Spring Cloud Gateway 預設就會代理服務中心的所有服務。

步驟一:建立專案

  1. 選擇 Gateway 和 Consul

步驟二:配置 src/main/resources/application.yml 檔案

  1. spring.cloud.gateway.discovery.locator.enabled :是否與服務註冊和發現元件進行結合,通過 serviceId 轉發到具體的服務例項。預設為 false,設為 true 便開啟通過服務中心的自動根據 serviceId 建立路由的功能。
  2. 指定註冊中心的地址,以便使用服務發現功能
spring.cloud.consul.host=127.0.0.1
spring.cloud.consul.port=8500
# 設定不需要註冊到 consul 中
spring.cloud.consul.discovery.register=false
複製程式碼

步驟三:建立 Consul 容器

1.映象官方網址:hub.docker.com/_/consul

2.pull 映象:

docker pull consul:1.6.0
複製程式碼

3.建立容器(預設http管理埠:8500)

docker run -p 8500:8500 consul:1.6.0
複製程式碼

4.訪問管理網址

http://localhost:8500/
複製程式碼

步驟四:啟動服務端

  1. 執行專案:github.com/cag2050/spr…

步驟五:驗證服務閘道器轉發成功

  1. 專案 spring_cloud_consul_producer1_demo 的 /hello 服務是:http://localhost:8501/hello ,訪問:http://localhost:8506/service -producer/hello ,正常返回類似文字:hello,說明服務閘道器轉發成功。

步驟六:Filter 的使用:使用 AddRequestParameter GatewayFilter 在請求中新增指定引數

  1. 修改 src/main/resources/application.yml,新增 routes 部分
  2. 訪問地址 http://localhost:8501/foo 頁面返回類似:引數 foo 的值是:null,說明並沒有接受到引數 foo;通過閘道器來呼叫此服務,瀏覽器訪問地址 http://localhost:8506/foo 頁面返回類似:引數 foo 的值是:bar,說明成功接收到引數 foo 的值 bar,證明閘道器在轉發的過程中已經通過 filter 添加了設定的引數和值。

步驟七:服務化路由轉發

  1. 再啟動服務端:github.com/cag2050/spr…
  2. 修改 src/main/resources/application.yml,將uri: http://localhost:8501 修改成 uri: lb://service-producer,瀏覽器訪問地址 http ://localhost:8506/foo,頁面交替出現:引數 foo 的值是:bar,from port:8501引數 foo 的值是:bar,from port:8502,證明請求依據均勻轉發到後端服務,並且後端服務均接收到了 filter 增加的引數 foo 值。

參考

參考資料 備註 網址
springcloud(十六):服務閘道器 Spring Cloud GateWay 服務化和過濾器 此參考資料,專案裡使用的註冊中心是 Eureka。 www.ityouknow.com/springcloud…

程式碼倉庫:github.com/cag2050/spr…