zuul转发后服务取不到请求路径的解决

zuul转发后服务取不到请求路径 问题
希望通过获取不同的路径中的项目名,动态设置数据源,但是经过zuul网关后,在后面的服务中获取不到请求路径。
解决
通过Header:x-forwarded-prefix获取
测试代码:

@GetMapping("/a")public String a(HttpServletRequest request) {StringBuilder result = new StringBuilder(); result.append("getMethod:" + request.getMethod() + "\n\r"); result.append("getRequestURL:" + request.getRequestURL() + "\n\r"); result.append("getServletPath:" + request.getServletPath() + "\n\r"); result.append("getContextPath:" + request.getContextPath() + "\n\r"); result.append("getPathInfo:" + request.getPathInfo() + "\n\r"); result.append("---------------------------------------------------" + "\n\r"); Enumeration es = request.getHeaderNames(); while (es.hasMoreElements()) {result.append(es.nextElement() + ":" + request.getHeader(es.nextElement()) + "\n\r"); }return result.toString(); }

返回结果:
zuul转发后服务取不到请求路径的解决
文章图片

路径中标红的地方,和x-forwarded-prefix头部里的内容是一样的,所以使用request.getHeader('x-forwarded-prefix')就可以获取到当前访问的项目,然后做区分。
思考
推测是因为zuul转发请求的时候用的代理,本地相当于直接访问http://localhost:9070/a,所以就获取不到最开始输入的路径,而x-forwarded-prefix这个头部是用来记录请求最初从浏览器发出时的访问地址
zuul 地址转发问题 最近在学习spring cloud,使用zuul过程中发现地址并没转发成功,页面一直报错404.
使用的Spring cloud版本为最新版Greenwich
zuul中配置文件内容是
server:port: 8180spring:application:name: zuul-testzuul:routes:hello:path: /hello/**url: http://localhost:9180/

期望的是当web请求http://localhost:8180/hello?name=world 时能跳转到http://localhost:9180/hello?neam=world 打印出"hello world",然而事实上并没有,出错,页面提示404.
开始以为是Spring cloud版本太高,就把纯洁的微笑博客中的demo下载下来测试,发现依然如此。
怀疑zuul的请求是直接跳转到http://localhost:9180/ 但是没有加上上下文"hello"
所以将配置更改如下:
server:port: 8180spring:application:name: zuul-testzuul:routes:hello:path: /hello/**url: http://localhost:9180/hello

请求跳转成功。
毕竟是自己的猜测,还是需要代码支持,所以断点,调试源码进入查看.
在org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter#run方法中通过
String uri = this.helper.buildZuulRequestURI(request);

解析出uri=“”,然后通过当前类中的forward方法组织请求参数并转发.
源码如下
zuul转发后服务取不到请求路径的解决
文章图片

重要是图中红框部分,如果你的转发地址没有带上上下文,host.getPath()获取的值将为"",与之前获取的uri拼接后为"".
通过323行
buildHttpRequest(verb, uri, entity, headers, params,request);

获取的httpRequest中的uri将会是?name=world,请求转发地址变成http://localhost:9180/?name=world,当然会404了。
【zuul转发后服务取不到请求路径的解决】以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读