Spring Cloud Gateway 网关组件及搭建实例
工作流程
- 客户端将请求发送到 Spring Cloud Gateway 上。
- Spring Cloud Gateway 通过 Gateway Handler Mapping 找到与请求相匹配的路由,将其发送给 Gateway Web Handler。
- 过滤器可以在响应返回客户端之前,对响应进行拦截和再处理,例如修改响应内容或响应头、日志输出、流量监控等。
- 响应原路返回给客户端。
动态路由
可以在配置文件中,将 Route 的 uri 地址修改为形式 lb://service-name
-
lb:uri 的协议,表示开启 Spring Cloud Gateway 的负载均衡功能。 service-name:服务名,Spring Cloud Gateway 会根据它获取到具体的微服务地址。
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 网关服务中不能引入 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 测试
- Websocket Demo 测试 1. test Demo wscat -l 9000 # 在本地9000端口启动websocket服务监听 ws://localhost:9527/echo # 使用postman测试收发信息情况