Spring Cloud Gateway核心概念和工作原理-Part 1
Spring Cloud Gateway的路由断言(Predicate)-Part 2
Spring Cloud Gateway是Spring官方基于Spring 5.0,Spring Boot 2.0和Project Reactor等技术开发的网关,Spring Cloud Gateway旨在为微服务架构提供一种简单而有效的统一的API路由管理方式。Spring Cloud Gateway作为Spring Cloud生态系中的网关,目标是替代Netflix ZUUL,其不仅提供统一的路由方式,并且基于Filter链的方式提供了网关基本的功能,例如:安全,监控/埋点,和限流等。
基于服务发现的默认路由规则
Gateway基于服务发现的路由规则和Zuul的设计类似,但也有差别。
如果把Gateway 注册到Eureka上,通过网关转发服务调用时,默认需要大写的serviceId/*,服务名默认必须大写,否则会出现404错误。如果需要使用小写的服务名(如Zuul 网关),可以在配置文件中添加spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true 来配置解决。
1. 在Spring Cloud Gateway 项目中,添加如下依赖。
其中添加actuator jar 包,是为了查看Spring Cloud Gateway 自动为服务消费者创建的路由信息。
引入 eureka-client jar包,是为了让gateway 注册到Eureka Server上。
org.springframework.cloud
spring-cloud-starter-gateway
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.boot
spring-boot-starter-actuator
2. 创建application.yml 配置文件
spring:
application:
name: sc-gateway-server
cloud:
gateway:
discovery:
locator:
enabled: true
#lowerCaseServiceId: true
server:
port: 9000 #网关服务监听 9000 端口
eureka:
client:
service-url: #指定注册中心的地址,以便使用服务发现功能
defaultZone: http://localhost:8761/eureka/
logging:
level: #调整相关包的 log 级别,以便排查问题
org.springframework.cloud.gateway: debug
management:
endpoints:
web:
exposure:
include: '*'
security:
enabled: false
其中配置项说明:
spring.cloud.gateway.discovery.locator.enabled = true (默认为false) 开启基于服务发现的默认路由规则,可以通过serviceId 转发到具体的服务实例。
spring.cloud.gateway.discovery.locator.lowerCaseServiceId = true(默认为false)当注册中心为 Eureka时,设置为 true表示开启小写的serviceId 进行基于服务路由的转发。
logging.level 设置相关包的 log 级别,方便排查问题。
3. 启动应用测试
演示项目中,包括Eureka,Gateway,ServiceProvider,ServiceConsumer等等应用。
访问 http://localhost:9000/sc-consumer/hello/rickie
可以成功进行转发,调用服务提供者。
访问 http://localhost:9000/actuator/gateway/routes
查看返回的路由信息。看到Spring Cloud Gateway 自动添加的路由信息。
当把 spring.cloud.gateway.discovery.locator.lowerCaseServiceId = true 注释掉,默认为 false。
此时,访问 http://localhost:9000/sc-consumer/hello/rickie,就会出现 404 错误。
访问 http://localhost:9000/actuator/gateway/routes
查看返回的路由信息。看到Spring Cloud Gateway 自动添加的路由信息。此时发现serviceId 需要大写,才能正确路由转发。
http://localhost:9000/SC-CONSUMER/hello/rickie
完整的演示项目代码:
https://github.com/rickiechina/spring-cloud-code/tree/master/ch18-1