SpringCloud Gateway 测试问题解决

本文针对于测试环境SpringCloud Gateway问题解决。html

1.背景介绍

本文遇到的问题都是在测试环境真正遇到的问题,不必定试用于全部人,仅作一次记录,便于遇到一样问题的干掉这些问题。前端

使用版本:SpringCloud 2.0.0.RELEASEjava

1.1 Gateway配置

以前系统是由阿里云SLB直接分发到几台生产服务器,可是通过研究,决定在中间加一层网关,也就是阿里云SLB分发流量到Gateway到下游服务。可是又因为种种缘由,决定使用Host方式进行拦截处理,如下为部分配置代码:react

spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
        - id: test_client
          uri: lb://TEST-CLIENT
          predicates:
            - Host=www.dalaoyang.cn
          order: 1
          filters:
            - DalaoyangAuth
            
复制代码

注意,其中部份内容并不是真实环境内容,可是场景绝对真实,如:jquery

  • test_client:routes的ID。
  • uri:这里使用的Eureka内的application name
  • Host:须要拦截的域名
  • filters:域名前缀

1.2 Gateway过滤器

过滤器内容以下,稍后介绍:git

@Component
public class DalaoyangAuthFilterFactory  extends AbstractGatewayFilterFactory<Object> {
    private static final Logger logger = LoggerFactory.getLogger(DalaoyangAuthFilterFactory.class);

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest host = exchange.getRequest().mutate().headers(httpHeaders -> {
                httpHeaders.remove("gate_way_auth");
                httpHeaders.add("gate_way_auth", "yes");
            }).build();
            //将如今的request 变成 change对象
            ServerWebExchange build = exchange.mutate().request(host).build();
            return chain.filter(build);
        };
    }
}
复制代码

1.3 下游服务拦截器

下游服务拦截器大体内容以下,这段代码是原有的代码,这个功能大概就是加载公共的属性basePath,用于加载静态资源,好比前端的jquery.js,根据域名判断,而后选择是加载为http://127.0.0.1:8080/jquery.js仍是https://www.dalaoyang.cn/jquery.js这种:github

public class GlobalInterceptorAdapter extends HandlerInterceptorAdapter {

    private static Logger logger = LoggerFactory.getLogger(GlobalInterceptorAdapter.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws
            Exception {
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int port = request.getServerPort();
        String path = request.getContextPath();
        String basePath = "";
        if(serverName.indexOf("www.dalaoyang.cn")!=-1){
        	basePath = "//" + serverName + path;
        }else {
        	basePath = scheme + "://" + serverName + ":" + port + path;
        }
        if (logger.isDebugEnabled()) {
            logger.debug(basePath);
        }
        request.setAttribute("basePath", basePath);
        return true;
    }

}
复制代码

1.4 下游服务用户过滤器

这段代码也是原有的代码,用户Session过滤器,这个完整内容不少,只截取遇到问题的片断,大体内容就是判断用户是否在其余地方登陆,若是登陆了就弹出的固定的提示页面,内容以下:spring

String url = null;
ApplicationConfig applicationConfig0 = getApplicationConfig();
if(applicationConfig0 != null) {
	String scheme = applicationConfig0.getUrlScheme();
    if(scheme != null) {
	    String requestUrl = request.getRequestURL().toString();
		    if(requestUrl != null && requestUrl.length() > 8) {
				requestUrl = requestUrl.substring(requestUrl.indexOf(":"), 
										requestUrl.indexOf("/", 8));
				url = scheme + requestUrl;
			}
	}
}
if(url != null) {
	response.sendRedirect(url + request.getContextPath() + "/session-time-out");
} else {
	response.sendRedirect(request.getContextPath() + "/session-time-out");
}
复制代码

1.5 跳转流程

跳转以下:浏览器

1.域名指向了Gateway地址。
2.在浏览器使用域名访问Gateway,被Gateway转发到下游服务,返回对应响应。bash

2.问题一 下游服务没法获取域名

在使用上述配置后,使用request.getServerName()方法已经没法获取到域名了,通过测试,获取到的是服务器的ip地址,致使虽然页面能够正常跳转,可是没法获取到正确的域名,致使静态资源加载有问题。

在网上请教了不少人,本想看看是否是什么地方没有设置对,可是后台仍是采起大多数人的建议,在header中加入一个域名信息,修改后Gateway过滤器以下:

@Component
public class DalaoyangAuthFilterFactory  extends AbstractGatewayFilterFactory<Object> {
    private static final Logger logger = LoggerFactory.getLogger(DalaoyangAuthFilterFactory.class);

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest host = exchange.getRequest().mutate().headers(httpHeaders -> {
                httpHeaders.remove("gate_way_auth");
                httpHeaders.add("gate_way_auth", "yes");
                
                httpHeaders.add("realServerName",
                exchange.getRequest().getURI().getHost());
                logger.info("headers:" + httpHeaders.toString());
            }).build();
            //将如今的request 变成 change对象
            ServerWebExchange build = exchange.mutate().request(host).build();
            return chain.filter(build);
        };
    }
}
复制代码

很容易看到,就是以下这句话:

httpHeaders.add("realServerName",
              exchange.getRequest().getURI().getHost());
复制代码

下游服务过滤修改成:

public class GlobalInterceptorAdapter extends HandlerInterceptorAdapter {
    private static Logger logger = LoggerFactory.getLogger(GlobalInterceptorAdapter.class);
    private final String TEST_SERVERNAME = "www.dalaoyang.cn";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws
            Exception {
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        String realServerName = request.getHeader("realServerName");
        int port = request.getServerPort();
        String path = request.getContextPath();
        String basePath = "";
        if((!StringUtils.isBlank(realServerName))){
            if(realServerName.contains(TEST_SERVERNAME)){
                basePath = "//" + realServerName + path;
            }
        }else {
            basePath = scheme + "://" + serverName + ":" + port + path;
        }
        if (logger.isDebugEnabled()) {
            logger.debug(basePath);
        }
        request.setAttribute("basePath", basePath);
        return true;
    }
}
复制代码

其实大体内容就是,使用以下方式获取域名:

String realServerName = request.getHeader("realServerName");
复制代码

到此,问题解决了,大部份内容跳转正常。

3.问题二 NPE异常

部分请求,通过路由访问报以下错误。

2018-06-20 01:26:04.254 ERROR 1 --- [reactor-http-client-epoll-11] .a.w.r.e.DefaultErrorWebExceptionHandler : Failed to handle request [DELETE http://localhost:8080/entity/5b29ad2cb3cb1f00010a1546]

java.lang.NullPointerException: null
        at java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011) ~[na:1.8.0_111]
        at java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006) ~[na:1.8.0_111]
        at org.springframework.cloud.gateway.filter.NettyRoutingFilter.lambda$filter$3(NettyRoutingFilter.java:117) ~[spring-cloud-gateway-core-2.0.0.RELEASE.jar!/:2.0.0.RELEASE]
        at reactor.core.publisher.FluxPeek$PeekSubscriber.onNext(FluxPeek.java:177) ~[reactor-core-3.1.8.RELEASE.jar!/:3.1.8.RELEASE]
        at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:108) ~[reactor-core-3.1.8.RELEASE.jar!/:3.1.8.RELEASE]
        at reactor.core.publisher.FluxRetryPredicate$RetryPredicateSubscriber.onNext(FluxRetryPredicate.java:81) ~[reactor-core-3.1.8.RELEASE.jar!/:3.1.8.RELEASE]
        at reactor.core.publisher.MonoCreate$DefaultMonoSink.success(MonoCreate.java:146) ~[reactor-core-3.1.8.RELEASE.jar!/:3.1.8.RELEASE]
        at reactor.ipc.netty.channel.PooledClientContextHandler.fireContextActive(PooledClientContextHandler.java:85) ~[reactor-netty-0.7.8.RELEASE.jar!/:0.7.8.RELEASE]
        at reactor.ipc.netty.http.client.HttpClientOperations.onInboundNext(HttpClientOperations.java:578) ~[reactor-netty-0.7.8.RELEASE.jar!/:0.7.8.RELEASE]
        at reactor.ipc.netty.channel.ChannelOperationsHandler.channelRead(ChannelOperationsHandler.java:136) ~[reactor-netty-0.7.8.RELEASE.jar!/:0.7.8.RELEASE]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) ~[netty-transport-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) ~[netty-transport-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) ~[netty-transport-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:438) ~[netty-transport-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:310) ~[netty-codec-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:284) ~[netty-codec-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:253) ~[netty-transport-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) ~[netty-transport-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) ~[netty-transport-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) ~[netty-transport-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1434) ~[netty-transport-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) ~[netty-transport-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) ~[netty-transport-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:965) ~[netty-transport-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:808) ~[netty-transport-native-epoll-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:408) ~[netty-transport-native-epoll-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:308) ~[netty-transport-native-epoll-4.1.25.Final.jar!/:4.1.25.Final]
        at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:884) ~[netty-common-4.1.25.Final.jar!/:4.1.25.Final]
        at java.lang.Thread.run(Thread.java:745) ~[na:1.8.0_111]
复制代码

遇到问题后,没有很慌,打开了百度查了查(微笑)。百度没让我很失望,基本上没啥答复,而后谷歌了一下,看到了github上的一个issues,大体内容感受是SpringCloud Gateway 2.0.0.RELEASE版本有些问题,升级一下版本就行了,如图。

Github issues地址:

github.com/spring-clou… github.com/spring-clou…

说实话,感受是版本问题,可是又看到了一篇国人的文章,地址是:xiaoqiangge.com/aritcle/154…,问题大体相似,加了一下博主的微信,请教了一下,大体了解到了,升级了一下版本,问题解决。

感谢小强哥!!!

4.问题三 下游用户过滤器跳转失效

问题是这样的,刚刚介绍了,用户在其余地方登陆会自动跳转至一个界面提示给用户,发现问题是没法跳转。

查看gateway日志,大概提示了这样一句话,以下:

Unhandled failure: Connection has been closed, response already set (status=302)
复制代码

从内容大体能够看出,重定向有问题,想到了在用户过滤器中最后的重定向,决定在这里下手,修改后内容以下:

String scheme = request.getScheme();
String serverName = request.getServerName();
String realServerName = request.getHeader("realServerName");
int port = request.getServerPort();
String path = request.getContextPath();
String basePath = "";
if((!StringUtils.isEmpty(realServerName))){
        if(realServerName.contains(TEST_SERVERNAME)){
		basePath = "https://" + realServerName + path;
	}else {
		basePath = scheme + "://" + serverName + ":" + port + path;
	}
response.sendRedirect(basePath + "/session-time-out");
复制代码

问题也解决了,目前还在踩坑测试中,若是你们有相似经验能够一块儿探讨。

相关文章
相关标签/搜索