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官方案例)
org.springframework.cloud spring-cloud-starter-gateway
配置 application.yml 文件
test:# hostport: httpbin.org:80# hostport: localhost:5000# uri: http://${test.hostport}# uri: lb://httpbinuri: http://localhost:8001spring:jmx:enabled: falsecloud:gateway:default-filters:# - PrefixPath=/httpbin- PrefixPath=/dept- AddResponseHeader=X-Response-Default-Foo, Default-Barroutes:# =====================================# to run server# $ wscat --listen 9000# to run client# $ wscat --connect ws://localhost:8080/echo- id: websocket_testuri: ws://localhost:9000order: 9000predicates:- Path=/echo- id: websocket_testuri: ws://localhost:8001order: 9000predicates:- Path=/dept# =====================================- id: default_path_to_httpbinuri: ${test.uri}order: 10000predicates:- Path=/**logging:level:org.springframework.cloud.gateway: TRACEorg.springframework.http.server.reactive: DEBUGorg.springframework.web.reactive: DEBUGreactor.ipc.netty: DEBUGreactor.netty: DEBUGmanagement.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 Demows://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 (史上最全)