上一篇介紹有關API Gateway,現在要將模組加進此專案





修改一下版本



接下來
要開啟註冊服務

然後在application.properties新增設定
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
spring.application.name=yumall-gateway
server.port=88
然後到nacos新增名稱空間,讓gateway也可以動態配置

再新增bootstrap.properties檔案,然後新增設定
spring.application.name=yumall-gateway
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.cloud.nacos.config.namespace=662556cd-a3b6-4ff7-be76-0b0f20341b85
這時候啟動專案
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
結果發現有錯誤,原因是因為此專案有依賴於common project,而裡面有mybatis-plus的資料庫的設定,所以要先將這部分排除,在應用啟動的地方做設定

再一次重新啟動,可以看到gateway使用netty來做的。

現在要做gateway的設定,來測試某些規則看看,新增一個application.yml
spring:
cloud:
gateway:
routes:
- id: test_route
uri: https://google.com.tw
predicates:
- Query=url,google
- id: yahoo_route
uri: https://yahoo.com.tw
predicates:
- Query=ya
設定檔中規則可以是多個的,所以才會是routes,原始碼中可以看到是一個List

然後每一個路由在官方介紹中,必須有個唯一ID,然後uri的設定就是要去的地方,然後斷言(predicates)的部分也是參照官方的範例去做,使用Query這種方式的斷言,這個方式的意思就是說在Query的等號後面是請求參數的名稱,而逗號後面是請求參數的值,而且這個值也可以使用正規表達式去寫。
設定好之後重啟服務,並在網址列輸入剛剛設定的第一個規則:http://127.0.0.1:88/?url=google
此時就會導向到第一個規則指定的地方

然後再測試第二個規則:http://127.0.0.1:88/?ya
一樣會導向指定的地方
