Spring Cloud Gateway接收到https请求,根据路由规则转发给后台微服务,但是默认情况下,转发给后台微服务时,仍然是https请求,这就要求后台微服务需要配置ssl,并且每台服务器都需要有域名,这名下是不太实际的,正常情况下,一个网站只有对外拍路的网关是通过域名访问,转发给后台微服务时,则是采用IP地址。
SpringCloud Zuul默认情况下就会帮我们实现https转换为http,gatewy需要我们自行添加可过滤器实现转换:
我只是个搬砖的,参考大佬博客:
https://www.jianshu.com/p/5a36129399f2
这位大佬分析了源码,并给出了解决方案:
SpringCloud Gateway https请求 转换为http 路由给后台微服务
添加过滤器:
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import java.net.URI;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;
@Component
public class SchemeFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
Object uriObj = exchange.getAttributes().get(GATEWAY_REQUEST_URL_ATTR);
if (uriObj != null) {
URI uri = (URI) uriObj;
uri = this.upgradeConnection(uri, "http");
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, uri);
}
return chain.filter(exchange);
}
private URI upgradeConnection(URI uri, String scheme) {
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUri(uri).scheme(scheme);
if (uri.getRawQuery() != null) {
// When building the URI, UriComponentsBuilder verify the allowed characters and does not
// support the '+' so we replace it for its equivalent '%20'.
// See issue https://jira.spring.io/browse/SPR-10172
uriComponentsBuilder.replaceQuery(uri.getRawQuery().replace("+", "%20"));
}
return uriComponentsBuilder.build(true).toUri();
}
@Override
public int getOrder() {
return 10101;
}
}
然后 。。。。。。就可以了
删除路由前缀:
再说一个Zuul与Gateway路由中的不同点
使用过Zuul,再使用Gateway会发现,Zuul会将路由前缀删除。例如:
- 对于Zuul:
假设Zuul路由配置为:spring.application.name=gateway-service-zuul server.port=8888 spring.cloud.client.ipAddress=网关IP地址 zuul.routes.basicService=/basicService/**
前端请求:http://网关IP地址:8888/basicService/getUserInfo
Zuul路由之后:http://basicService微服务IP地址:basicService端口号/getUserInfo
(删除了basicService) - 对于Gateway:
Gateway路由后:http://basicService微服务IP地址:basicService端口号/basicService/getUserInfo
(没有删除basicService) - 如果要实现与Zuul同样的效果,则需要加一个路径改写过滤器:
spring: cloud: gateway: routes: - id: neo_route uri: lb://basicService predicates: - Path=/basicService/** filters: - RewritePath=/basicService/(?<segment>.*), /$\{segment}
本文介绍了如何在SpringCloud Gateway中处理接收到的HTTPS请求,并将其转换为HTTP请求转发给后台微服务。由于默认情况下,Gateway不会自动进行这种转换,所以需要自定义过滤器来实现。此外,文章还提到了Gateway与Zuul在路由前缀处理上的区别,Zuul会自动删除路由前缀,而Gateway则需要额外配置路径改写过滤器来实现相同功能。
7184





