时间:2023-03-03 11:18:33 | 栏目:JAVA代码 | 点击:次
之前在用zuul网关的时候,请求几次然后连接就断开了。原因是因为http1.1之后,默认走的都是connection=keep-alive 长连接。但没有心跳维持,顾1分钟断开一次。但RestFul一般都是走短连接就行了。因此想着只要修改头部connection属性就行了.
就是在过滤器中修改Zuul的RequestContext ctx对象
//设置请求为短连接 ctx.addZuulRequestHeader("connection", "close");
再次请求之后发现
?纳尼,怎么还是长连接。那么说明可能是我的设置没有生效或者被覆盖掉了。遇到问题,除了度娘,跟着源码走一遭也是最好的方式。花了大半天时间,终于让我找到原因了。
原因是代理类ProxyRequestHelper里面有段逻辑。
public boolean isIncludedHeader(String headerName) { String name = headerName.toLowerCase(); RequestContext ctx = RequestContext.getCurrentContext(); if (ctx.containsKey(IGNORED_HEADERS)) { Object object = ctx.get(IGNORED_HEADERS); if (object instanceof Collection && ((Collection<?>) object).contains(name)) { return false; } } switch (name) { case "host": if(addHostHeader) { return true; } case "connection": case "content-length": case "server": case "transfer-encoding": case "x-application-context": return false; default: return true; } }
如果头部存在"connection": "content-length": "server": "transfer-encoding": "x-application-context"这些头的话都被跳过。不会被设置成功。应该是zuul自己的一个机制把。
那么问题找到了,该怎么修改呢?那么只能自定义路由了。继承并重写这个类。
1、实现自定义路由配置CustomZuulConfig
@Component public class CustomZuulConfig { @Autowired ZuulProperties zuulProperties; @Value("${servletPath}") private String servletPath; @Bean public CustomRouteLocator routeLocator() { CustomRouteLocator routeLocator = new CustomRouteLocator(servletPath, this.zuulProperties); return routeLocator; } }
2、实现自定义请求代理工具类 重写isIncludedHeader方法。
public class CustomRequestHelper extends ProxyRequestHelper { @Override public boolean isIncludedHeader(String headerName) { String name = headerName.toLowerCase(); RequestContext ctx = RequestContext.getCurrentContext(); if (ctx.containsKey(IGNORED_HEADERS)) { Object object = ctx.get(IGNORED_HEADERS); if (object instanceof Collection && ((Collection<?>)object).contains(name)) { return false; } } switch (name) { case "content-length": case "host": case "server": case "transfer-encoding": case "x-application-context": return false; default: return true; } } }
3、重写实现代理配置类
@Configuration @EnableZuulProxy public class CustomZuulProxyConfig extends ZuulProxyAutoConfiguration { @Bean @Override public SimpleHostRoutingFilter simpleHostRoutingFilter(ProxyRequestHelper helper, ZuulProperties zuulProperties, ApacheHttpClientConnectionManagerFactory connectionManagerFactory, ApacheHttpClientFactory httpClientFactory) { CustomRequestHelper customRequestHelper = new CustomRequestHelper(); return new SimpleHostRoutingFilter(customRequestHelper, zuulProperties, connectionManagerFactory, httpClientFactory); } }
然后重新启动,查看请求头。
?修改成功。所以说,学会通过看源码查问题,还是很重要的哈~