Gateway是Spring Cloud的一个组件,它提供了一种简单而有效的方式来将请求路由到不同的微服务中。Gateway还支持WebSocket代理,可以将WebSocket请求路由到后端的WebSocket服务器。
Spring Boot项目引入Gateway的pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
yml配置文件,gateway通过配置文件进行反向代理。以下为配置样例
server:
port: 8654
spring:
cloud:
gateway: # gateway网关配置
httpclient:
websocket:
max-frame-payload-length: 10485760
routes: # 配置路由
- id: service-router
# 动态路由:从(消费)注册中⼼获取对应服务的实例
uri: http://127.0.0.1:8081
predicates: # 当断言匹配成功后,则将请求转发给某个微服务
- Path=/ws/**
作为反向代理层,我们需要利用GlobalFilter对携带的信息进行解析和处理
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBufInputStream;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.headers.HttpHeadersFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.rea