这篇文章以案例的形式来讲解Spring Cloud Gateway如何配合服务注册中心进行路由转发。
1、系统架构
2、搭建子工程eureka-gateway
A.导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
B.配置文件application.yml
server:
port: 8081
spring:
application:
name: eureka-gateway
cloud:
gateway:
discovery:
locator:
enabled: true
lowerCaseServiceId: true
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
其中,spring.cloud.gateway.discovery.locator.enabled为true,表明gateway开启服务注册和发现的功能,并且spring cloud gateway自动根据服务发现为每一个服务创建了一个router,这个router将以服务名开头的请求路径转发到对应的服务。spring.cloud.gateway.discovery.locator.lowerCaseServiceId是将请求路径上的服务名配置为小写(因为服务注册的时候,向注册中心注册时将服务名转成大写的了),比如以/eureka-hello/*的请求路径被路由转发到服务名为eureka-hello的服务上。
C.启动测试
依次启动eureka-server、eureka-client、eureka-gateway
在浏览器上请求输入localhost:8081/eureka-hello/hello?name=1323,网页获取以下的响应:
hello 1323 ,i am from port:8762
在上面的例子中,向eureka-gateway发送的请求时,url必须带上服务名eureka-hello这个前缀,才能转发到eureka-hello上,转发之前会将eureka-hello去掉。
D.自定义路由
那么我能不能自定义请求路径呢,毕竟根据服务名有时过于太长,或者历史的原因不能根据服务名去路由,需要由自定义路径并转发到具体的服务上。答案是肯定的是可以的,只需要修改工程的配置文件application.yml,具体配置如下:
spring:
application:
name: eureka-gateway
cloud:
gateway:
discovery:
locator:
enabled: false
lowerCaseServiceId: true
routes:
- id: eureka-hello
uri: lb://EUREKA_HELLO
predicates:
- Path=/demo/**
filters:
- StripPrefix=1
在上面的配置中,配置了一个Path 的predict,将以/demo/**开头的请求都会转发到uri为lb://EUREKA_HELLO的地址上,lb://EUREKA_HELLO即eureka-hello服务的负载均衡地址,并用StripPrefix的filter 在转发之前将/demo去掉。同时将spring.cloud.gateway.discovery.locator.enabled改为false,如果不改的话,之前的localhost:8081/eureka-hello/hello?name=1323这样的请求地址也能正常访问,因为这时为每个服务创建了2个router。
在浏览器上请求localhost:8081/demo/hello?name=1323,浏览器返回以下的响应:
hello 1323 ,i am from port:8762
返回的结果跟我们预想的一样。