spring boot版本:2.1.10.RELEASE
spring cloud版本:Greenwich.SR4
1.添加pom依賴
<!-- spring gateway依賴 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<!-- eureka依賴 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2.配置服務路由
網上大部分採用 yml 配置,這裏採用 application.properties。
spring cloud gateway官方文檔
參考資料
# 暴露所有的gateway端點
management.endpoints.web.exposure.include=*
# 自動配置註冊中心中路由 默認 false關閉
spring.cloud.gateway.discovery.locator.enabled=false
# 開啓小寫驗證,默認feign根據服務名查找都是用的全大寫
spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true
# 設置路由id
spring.cloud.gateway.routes[0].id=jz-shop-product
# 設置路由uri uri以lb://開頭(lb代表從註冊中心獲取服務),
# 後面接的就是你需要轉發到的服務名稱,這個服務名稱必須跟eureka中的對應,否則會找不到服務
# 也可以是一個url
spring.cloud.gateway.routes[0].uri=lb://jz-shop-product
spring.cloud.gateway.routes[0].predicates[0]= Path=/shop-product/**
spring.cloud.gateway.routes[0].filters[0]= StripPrefix=1
spring.cloud.gateway.routes[1].id=jz-shop-cart
spring.cloud.gateway.routes[1].uri=lb://jz-shop-cart
spring.cloud.gateway.routes[1].predicates[0]= Path=/shop-cart/**
spring.cloud.gateway.routes[1].filters[0]= StripPrefix=1
注意:
- 這裏配置了兩個服務,如果用 predicates 配置了前綴,一定要用 StripPrefix 將前綴去掉,使url與服務中額url一致,否則會報404。
- 啓動類無需額外添加除 @SpringBootApplication 之外的任何註解。