Spring Cloud Gateway 是 Spring Cloud 团队基于 Spring 5.0、Spring Boot 2.0 和 Project Reactor 等技术开发的高性能 API 网关组件。Spring Cloud Gateway 旨在提供一种简单而有效的途径来发送 API,并为它们提供横切关注点,例如:安全性,监控/指标和弹性。
Spring Cloud Gateway 是基于 WebFlux 框架实现的,而 WebFlux 框架底层则使用了高性能的 Reactor 模式通信框架 Netty。它最主要的功能就是路由转发,在定义转发规则时主要涉及以下三个核心概念:

默认情况下,Spring Cloud Gateway 会根据服务注册中心(例如 Eureka Server)中维护的服务列表,以服务名(spring.application.name)作为路径创建动态路由进行转发,从而实现动态路由功能。
可以在配置文件中,将 Route 的 uri 地址修改为形式 lb://service-name
routes:
- id: provider_dept_list_routh #路由 id,没有固定规则,但唯一
uri: lb://MICROSERVICECLOUDPROVIDERDEPT #动态路由,使用服务名代替具体端口
Spring Cloud Gateway 提供了以下两种类型的过滤器,可以对请求和响应进行精细化控制。按照作用范围又可以划分为GatewayFilter、GlobalFilter。
filters:
- AddRequestParameter=X-Request-Id,1024
# 过滤器工厂会在匹配的请求头加上一对请求头,名称为 X-Request-Id,值为 1024
- PrefixPath=/dept # 在请求路径前面加上 /dept
在项目 pom.xml 中引入Spring Cloud Gateway依赖(Gateway官方案例)
<!--特别注意:在 gateway 网关服务中不能引入 spring-boot-starter-web 的依赖,否则会报错-->
<!-- Spring Cloud Gateway 网关组件依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
配置 application.yml 文件
test:
# hostport: httpbin.org:80
# hostport: localhost:5000
# uri: http://${test.hostport}
# uri: lb://httpbin
uri: http://localhost:8001
spring:
jmx:
enabled: false
cloud:
gateway:
default-filters:
# - PrefixPath=/httpbin
- PrefixPath=/dept
- AddResponseHeader=X-Response-Default-Foo, Default-Bar
routes:
# =====================================
# to run server
# $ wscat --listen 9000
# to run client
# $ wscat --connect ws://localhost:8080/echo
- id: websocket_test
uri: ws://localhost:9000
order: 9000
predicates:
- Path=/echo
- id: websocket_test
uri: ws://localhost:8001
order: 9000
predicates:
- Path=/dept
# =====================================
- id: default_path_to_httpbin
uri: ${test.uri}
order: 10000
predicates:
- Path=/**
logging:
level:
org.springframework.cloud.gateway: TRACE
org.springframework.http.server.reactive: DEBUG
org.springframework.web.reactive: DEBUG
reactor.ipc.netty: DEBUG
reactor.netty: DEBUG
management.endpoints.web.exposure.include: '*'
server:
port: 9527
Http Restful Demo 测试
1、服务提供者请求连接 http://localhost:8001/dept/list?uname=123
2、gateway网关请求转发 http://localhost:9527/list?uname=123

Websocket Demo 测试
1. test Demo
wscat -l 9000 # 在本地9000端口启动websocket服务监听
ws://localhost:9527/echo # 使用postman测试收发信息情况

2. test1 Demo
ws://localhost:8001/dept/test/websocket # 服务提供者请求连接
ws://localhost:9527/test/websocket # gateway网关请求转发


【参考链接】
1、Github : spring-cloud/spring-cloud-gateway
2、Gateway集成WebSocket 实现前后端通信
3、推荐一个websocket测试工具:wscat
4、spring cloud gateway-filter的那些事
5、SpringCloud gateway (史上最全)