今天就跟大家聊聊有关Springcloud中ZuulController如何使用,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
Springcloud的版本是Greenwich.SR2,Springboot版本是2.1.6.release.
最近使用到Springcloud的zuul,分析了下源码,记录下,如下的List-1,主要是zuulHandlerMapping方法,构造ZuulHandlerMapping时,传入的RouteLocator是CompositeRouteLocator,而this.zuulController()返回的是ZuulController类。
List-1
@Bean public ZuulController zuulController() { return new ZuulController(); } @Bean public ZuulHandlerMapping zuulHandlerMapping(RouteLocator routes) { ZuulHandlerMapping mapping = new ZuulHandlerMapping(routes, this.zuulController()); mapping.setErrorController(this.errorController); mapping.setCorsConfigurations(this.getCorsConfigurations()); return mapping; }
如下图1所示,ZuulHandlerMapping继承了AbstractUrlHandlerMapping,如果了解Springmvc,就对这个应该熟悉点了。ZuulHandlerMapping复写了父类的lookupHandler,目的是将url-->controller这个映射关系注册到Springmvc中,如List-2所示。
图1
如下List-2,registerHandlers方法中,遍历所有的Route,之后将这些Route的处理类设置为ZuulController。routeLocator的实现有三个,分别是SimpleRouteLocator、DiscoveryClientRouteLocator、DiscoveryClientRouteLocator。
List-2
private final ZuulController zuul; @Override protected Object lookupHandler(String urlPath, HttpServletRequest request) throws Exception { if (this.errorController != null && urlPath.equals(this.errorController.getErrorPath())) { return null; } if (isIgnoredPath(urlPath, this.routeLocator.getIgnoredPaths())) { return null; } RequestContext ctx = RequestContext.getCurrentContext(); if (ctx.containsKey("forward.to")) { return null; } if (this.dirty) { synchronized (this) { if (this.dirty) { registerHandlers(); this.dirty = false; } } } return super.lookupHandler(urlPath, request); } private void registerHandlers() { Collection<Route> routes = this.routeLocator.getRoutes(); if (routes.isEmpty()) { this.logger.warn("No routes found from RouteLocator"); } else { for (Route route : routes) { registerHandler(route.getFullPath(), this.zuul); } } }
上面分析,知道了由ZuulController来处理,那么来看下ZuulController,如下List-3所示,如果去看ZuulController的父类ServletWrappingController,会看到,是将请求交给ZuulServlet来处理,ZuulServlet和ZuulFilter是如何结合起来处理的,看另一篇博客。
List-3
public class ZuulController extends ServletWrappingController { public ZuulController() { setServletClass(ZuulServlet.class); setServletName("zuul"); setSupportedMethods((String[]) null); // Allow all } @Override public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { try { // We don't care about the other features of the base class, just want to // handle the request return super.handleRequestInternal(request, response); } finally { // @see com.netflix.zuul.context.ContextLifecycleFilter.doFilter RequestContext.getCurrentContext().unset(); } } }
到此,我们知道Zuul是如何将Route路由信息(我们在springboot application.yml中配置的)映射到ZuulController,而后ZuulController委托给ZuulServlet来处理。
看完上述内容,你们对Springcloud中ZuulController如何使用有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。