核心概念

Route(路由):

网关配置的基本组成模块,和Zuul的路由配置模块类似。一个Route模块由一个ID,一个目标URI,一组谓词(断言)和一组过滤器定义。如果断言为真,则路由匹配,目标URI会被访问。

Predicate(谓词):

即java.util.function.Predicate,通过Predicate实现路由匹配条件

Filter(过滤器)

和Zuul的过滤器在概念上类似,可以使用它拦截和修改请求,并且对上游的响应,进行二次处理。过滤器为org.springframework.cloud.gateway.filter.GatewayFilter类的实例。

配置

maven配置

pom.xml

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-gateway</artifactId>
  5. </dependency>
  6. </dependencies>

yml配置

application.yml

  1. server:
  2. port: 9201
  3. spring:
  4. cloud:
  5. gateway:
  6. routes:
  7. - id: user-cervice #路由的ID
  8. uri: http://localhost:8201/user/{id} #匹配后路由地址
  9. predicates: # 断言,路径相匹配的进行路由
  10. - Path=/user/{id}

配置中心

  1. server:
  2. port: 8080
  3. spring:
  4. application:
  5. name: gateway
  6. cloud:
  7. gateway:
  8. discovery:
  9. locator:
  10. enabled: true
  11. logging:
  12. level:
  13. org.springframework.cloud.gateway: trace
  14. org.springframework.http.server.reactive: debug
  15. org.springframework.web.reactive: debug
  16. reactor.ipc.netty: debug
  17. eureka:
  18. client:
  19. serviceUrl:
  20. defaultZone: http://localhost:8761/eureka/

spring.cloud.gateway.discovery.locator.enabled:表示是否与服务发现组件(register)进行结合,通过 serviceId(必须设置成大写)转发到具体的服务实例。默认为 false,设为 true 便开启通过服务中心的自动根据 serviceId 创建路由的功能。路由访问方式:http://Gateway_HOST:Gateway_PORT/ 大写的 serviceId/**,其中微服务应用名默认大写访问。
image.png
logging.level:日志配置策略。
然后我们启动服务注册中心、服务提供者、服务网关,访问地址:http://localhost:8080/EUREKACLIENT/index,我们可以看到和之前的界面完全一样。

路由谓词工厂

路由谓词工厂 (Route Predicate Factories),路由谓词工厂的作用是:符合Predicate的条件,就使用该路由的配置,否则就不管.

谓词工厂
After
Before
Between
Cookie
Header
Host
Method
Path
Query
RemoteAddr


过滤器Filter

StripPrefix


对指定数量的路径前缀进行去除的过滤器。

  1. spring:
  2. cloud:
  3. gateway:
  4. routes:
  5. - id: strip_prefix_route
  6. uri: http://localhost:8201
  7. predicates:
  8. - Path=/user-service/**
  9. filters:
  10. - StripPrefix=2


以上配置会把以/user-service/开头的请求的路径去除两位,通过curl工具使用以下命令进行测试。

  1. curl http://localhost:9201/user-service/a/user/1

相当于发起该请求:

  1. curl http://localhost:8201/user/1



PrefixPath


与StripPrefix过滤器恰好相反,会对原有路径进行增加操作的过滤器。
以上配置会对所有GET请求添加/user路径前缀,通过curl工具使用以下命令进行测试。

  1. curl http://localhost:9201/1

相当于发起该请求:

  1. curl http://localhost:8201/user/1

[

](http://localhost:8201/user/1)

参考

https://www.cnblogs.com/crazymakercircle/p/11704077.html
https://xinlichao.cn/back-end/java/spring-cloud-gateway/

https://segmentfault.com/a/1190000039390248