Zuul現在應用的已經非常少了,至少都在使用Spring Cloud Gateway。Zuul實作是基于Servlet這種阻塞是IO這種機制是通過建立更多的線程來彌補其不足;而Cloud Gateway則是基于反應式非阻塞式的,使用少量的線程來做更多的事。
1 收集路由
public class ZuulServerAutoConfiguration {
@Autowired
protected ZuulProperties zuulProperties;
@Autowired
protected ServerProperties server;
// 主
@Bean
@Primary
public CompositeRouteLocator primaryRouteLocator(
Collection<RouteLocator> routeLocators) {
return new CompositeRouteLocator(routeLocators);
}
@Bean
@ConditionalOnMissingBean(SimpleRouteLocator.class)
public SimpleRouteLocator simpleRouteLocator() {
return new SimpleRouteLocator(this.server.getServlet().getContextPath(), this.zuulProperties);
}
}
SimpleRouteLocator
public class SimpleRouteLocator implements RouteLocator, Ordered {
private ZuulProperties properties;
private String dispatcherServletPath = "/";
private String zuulServletPath;
private AtomicReference<Map<String, ZuulRoute>> routes = new AtomicReference<>();
// servletPath = server.servlet.contextPath 配置屬性值
public SimpleRouteLocator(String servletPath, ZuulProperties properties) {
this.properties = properties;
if (StringUtils.hasText(servletPath)) {
this.dispatcherServletPath = servletPath;
}
// 預設為:/zuul
this.zuulServletPath = properties.getServletPath();
}
// 該方法會在CompositeRouteLocator中調用,而本例的作用就是将ZuulRoute轉換為Route對象
@Override
public List<Route> getRoutes() {
List<Route> values = new ArrayList<>();
for (Entry<String, ZuulRoute> entry : getRoutesMap().entrySet()) {
ZuulRoute route = entry.getValue();
String path = route.getPath();
try {
// 将配置檔案中配置的ZuulRoute路由轉換為Route對象
values.add(getRoute(route, path));
}
}
return values;
}
protected Map<String, ZuulRoute> getRoutesMap() {
if (this.routes.get() == null) {
this.routes.set(locateRoutes());
}
return this.routes.get();
}
protected Map<String, ZuulRoute> locateRoutes() {
LinkedHashMap<String, ZuulRoute> routesMap = new LinkedHashMap<>();
// properties.getRouets擷取配置檔案中配置的所有路由
for (ZuulRoute route : this.properties.getRoutes().values()) {
routesMap.put(route.getPath(), route);
}
return routesMap;
}
protected Route getRoute(ZuulRoute route, String path) {
String targetPath = path;
// 擷取配置檔案的zuul.prefix屬性值
String prefix = this.properties.getPrefix();
if (prefix.endsWith("/")) {
// 删除 '/' 結尾的字元
prefix = prefix.substring(0, prefix.length() - 1);
}
// 判斷配置的路由path屬性值的開始字元串是不是以 '/prefix/'開頭,如:/api/
// 如果配置的path:/api/api-1/**則比對第一個條件,再判斷zuul.strip-prefix屬性值是否為true
if (path.startsWith(prefix + "/") && this.properties.isStripPrefix()) {
// 成立則會截取字元串删除'/prefix/'開頭的字元,則最終targetPath = /api-1/**
targetPath = path.substring(prefix.length());
}
// 如果配置為true
if (route.isStripPrefix()) {
// 知道path中第一個'*'
int index = route.getPath().indexOf("*") - 1;
// 如果存在
if (index > 0) {
// 截取第一個'*'之前的字元串
// 如上:最終routePrefix = /api-1
String routePrefix = route.getPath().substring(0, index);
// 結合上面:targetPath = /**
targetPath = targetPath.replaceFirst(routePrefix, "");
// 結合上面:prefix = /api + /api-1 = /api/api-1
prefix = prefix + routePrefix;
}
}
// 上面的路徑處理就是将配置的zuul.prefix + zuul.routes.xx.path
Boolean retryable = this.properties.getRetryable();
if (route.getRetryable() != null) {
retryable = route.getRetryable();
}
// 建構Route對象
return new Route(route.getId(), targetPath, route.getLocation(), prefix,
retryable,
route.isCustomSensitiveHeaders() ? route.getSensitiveHeaders() : null,
route.isStripPrefix());
}
}
CompositeRouteLocator
public class CompositeRouteLocator implements RefreshableRouteLocator {
private final Collection<? extends RouteLocator> routeLocators;
private ArrayList<RouteLocator> rl;
// 收集所有RouteLocator,如上面的SimpleRouteLocator
public CompositeRouteLocator(Collection<? extends RouteLocator> routeLocators) {
rl = new ArrayList<>(routeLocators);
AnnotationAwareOrderComparator.sort(rl);
this.routeLocators = rl;
}
public List<Route> getRoutes() {
List<Route> route = new ArrayList<>();
for (RouteLocator locator : routeLocators) {
route.addAll(locator.getRoutes());
}
return route;
}
}
這裡的RouteLocator有何用,下面會見到。
2 注冊HandlerMapping
Zuul會注冊自身特定的ZuulHandlerMapping對象。
public class ZuulServerAutoConfiguration {
// Controller接口;一個controller接口可以通過實作Controller或AbstractController接口來實作
@Bean
public ZuulController zuulController() {
return new ZuulController();
}
@Bean
public ZuulHandlerMapping zuulHandlerMapping(RouteLocator routes,
ZuulController zuulController) {
// HandlerMapping中注入了RouteLocator,也就是上面的CompositeRouteLocator對象
ZuulHandlerMapping mapping = new ZuulHandlerMapping(routes, zuulController);
mapping.setErrorController(this.errorController);
mapping.setCorsConfigurations(getCorsConfigurations());
return mapping;
}
}
zuulController
public class ZuulController extends ServletWrappingController {
public ZuulController() {
// 調用父類的方法設定父類的成員變量servletClass 該Class是個Servlet
// 在下面會看到如何使用ZuulServlet對象
setServletClass(ZuulServlet.class);
setServletName("zuul");
// 支援任意的請求方法
setSupportedMethods((String[]) null); // Allow all
}
// 該方法是Controller接口的核心方法
@Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
try {
return super.handleRequestInternal(request, response);
}
}
}
ZuulHandlerMapping
HandlerMapping作用就是從通過請求的URI查找到合适的處理句柄,找到就之間傳回,接下來就是由HandlerAdapter進行實際的處理了
public class ZuulHandlerMapping extends AbstractUrlHandlerMapping {
private volatile boolean dirty = true;
private final ZuulController zuul;
public ZuulHandlerMapping(RouteLocator routeLocator, ZuulController zuul) {
this.routeLocator = routeLocator;
this.zuul = zuul;
// 優先級就很高了,值越小優先級越高
setOrder(-200);
}
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) {
// 首次時dirty為true,這時候就會注冊處理句柄了
registerHandlers();
this.dirty = false;
}
}
}
// 調用父類的方法查找合适的請求處理器,從父類handlerMap屬性(Map)集合中查找
return super.lookupHandler(urlPath, request);
}
private void registerHandlers() {
// 這裡就調用了上面CompositeRouteLocator#getRoutes,這樣就得到了所有的路由資訊
Collection<Route> routes = this.routeLocator.getRoutes();
if (routes.isEmpty()) {
this.logger.warn("No routes found from RouteLocator");
} else {
for (Route route : routes) {
// 注意:所有的請求路徑都對應同一個Handler也就是上面的ZuulController對象
// 到這就知道了所有的路由請求都會被ZuulController處理
// 調用父類方法,将路由資訊添加到父類handlerMap屬性中(Map)集合
registerHandler(route.getFullPath(), this.zuul);
}
}
}
}
3 路由調用
一個請求過來時,通過上面的ZuulHandlerMapping對象找到了合适的處理句柄也就是ZuulController,接下來就是由合适的HandlerAdapter進行真正的調用了。
現在确定了handler對象是ZuulController,接下來就是檢視那個HandlerAdatper能夠進行處理了。
ZuulController實作了Controller接口,能夠處理該類型的是:SimpleControllerHandlerAdaper。
public class SimpleControllerHandlerAdapter implements HandlerAdapter {
public boolean supports(Object handler) {
return (handler instanceof Controller);
}
@Override
@Nullable
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// 調用ZuulController#handleRequest方法
return ((Controller) handler).handleRequest(request, response);
}
}
回到ZuulController
public class ZuulController extends ServletWrappingController {
public ZuulController() {
// 記住這裡我們給父類屬性servletClass 設定為ZuulServlet
setServletClass(ZuulServlet.class);
setServletName("zuul");
// 支援任意方法
setSupportedMethods((String[]) null); // Allow all
}
@Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
try {
// 調用父類方法
return super.handleRequestInternal(request, response);
} finally {
// @see com.netflix.zuul.context.ContextLifecycleFilter.doFilter
RequestContext.getCurrentContext().unset();
}
}
}
public class ServletWrappingController extends AbstractController
implements BeanNameAware, InitializingBean, DisposableBean {
private Class<? extends Servlet> servletClass;
public void setServletClass(Class<? extends Servlet> servletClass) {
this.servletClass = servletClass;
}
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception {
// 調用ZuulServlet#service方法(具體的處理還是通過ZuulServlet處理)
this.servletInstance.service(request, response);
return null;
}
// 該Bean在初始化解決會通過serveltClass執行個體化ZuulServlet對象。
public void afterPropertiesSet() throws Exception {
if (this.servletClass == null) {
throw new IllegalArgumentException("'servletClass' is required");
}
if (this.servletName == null) {
this.servletName = this.beanName;
}
// 執行個體化
this.servletInstance = ReflectionUtils.accessibleConstructor(this.servletClass).newInstance();
// servlet初始化
this.servletInstance.init(new DelegatingServletConfig());
}
}
ZuulServlet
public class ZuulServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
String bufferReqsStr = config.getInitParameter("buffer-requests");
boolean bufferReqs = bufferReqsStr != null && bufferReqsStr.equals("true") ? true : false;
zuulRunner = new ZuulRunner(bufferReqs);
}
// 任意階段發生了異常都會執行error,post階段
public void service(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse) throws ServletException, IOException {
try {
init((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse);
RequestContext context = RequestContext.getCurrentContext();
context.setZuulEngineRan();
try {
// pre節點的ZuulFilter執行
preRoute();
} catch (ZuulException e) {
// error階段
error(e);
postRoute();
return;
}
try {
// route階段的路由執行
// 這裡其實就是通過網絡api調用目标服務的接口了
// 我們可以實作自己的處理api接口的調用
// 如果你真的自己實作了,那麼請記得最後執行這行代碼
// context.setRouteHost(null); // prevent SimpleHostRoutingFilter from running
// 這樣就阻止預設的執行了
// SimpleHostRoutingFilter 網絡請求處理使用的Apache Client
// 在該節點得到資料後我們可以通過ProxyRequestHelper工具類将結果(InputStream)儲存到
// RequestContext中,一切順利在post階段就會由SendResponseFilter從RequestContext中擷取InputStream,然後寫到用戶端
route();
} catch (ZuulException e) {
error(e);
// 發生了異常也會執行
postRoute();
return;
}
try {
// post階段
// 比如:系統提供的SendResponseFilter過濾器就是真正往用戶端開始寫資料了。
postRoute();
} catch (ZuulException e) {
error(e);
return;
}
} catch (Throwable e) {
error(new ZuulException(e, 500, "UNHANDLED_EXCEPTION_" + e.getClass().getName()));
} finally {
RequestContext.getCurrentContext().unset();
}
}
void init(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
// 将request,response都進行了Wrapper(HttpServletRequestWrapper, HttpServletResponseWrapper)
zuulRunner.init(servletRequest, servletResponse);
}
}
在上面就看到了各個階段的Filter的執行。這裡需要注意一點,在每個階段執行的時候都會通過FilterLoader來擷取對應階段的ZuulFilter。
這個FilterLoader對象并不是一個被容器管理的對象,下面來看這個FilterLoader是如何收集所有ZuulFilter。
public class ZuulServerAutoConfiguration {
@Configuration(proxyBeanMethods = false)
protected static class ZuulFilterConfiguration {
// 擷取容器中所有的ZuulFilter
@Autowired
private Map<String, ZuulFilter> filters;
// 該Bean中有通過注解@PostConstruct标注的Bean在初始化階段執行的方法。
@Bean
public ZuulFilterInitializer zuulFilterInitializer(CounterFactory counterFactory,
TracerFactory tracerFactory) {
FilterLoader filterLoader = FilterLoader.getInstance();
FilterRegistry filterRegistry = FilterRegistry.instance();
return new ZuulFilterInitializer(this.filters, counterFactory, tracerFactory,
filterLoader, filterRegistry);
}
}
}
public class ZuulFilterInitializer {
private final Map<String, ZuulFilter> filters;
private final FilterLoader filterLoader;
private final FilterRegistry filterRegistry;
public ZuulFilterInitializer(Map<String, ZuulFilter> filters,
CounterFactory counterFactory, TracerFactory tracerFactory,
FilterLoader filterLoader, FilterRegistry filterRegistry) {
this.filters = filters;
this.counterFactory = counterFactory;
this.tracerFactory = tracerFactory;
this.filterLoader = filterLoader;
this.filterRegistry = filterRegistry;
}
// 該方法作用就是将所有的ZuulFilter添加到FilterRegistry中
@PostConstruct
public void contextInitialized() {
for (Map.Entry<String, ZuulFilter> entry : this.filters.entrySet()) {
// 将所有的ZuulFilter注冊到FilterRegistry中
filterRegistry.put(entry.getKey(), entry.getValue());
}
}
}
FilterLoader
public class FilterLoader {
public Object runFilters(String sType) throws Throwable {
boolean bResult = false;
// 擷取對應階段的ZuulFilter
List<ZuulFilter> list = FilterLoader.getInstance().getFiltersByType(sType);
if (list != null) {
for (int i = 0; i < list.size(); i++) {
ZuulFilter zuulFilter = list.get(i);
Object result = processZuulFilter(zuulFilter);
if (result != null && result instanceof Boolean) {
bResult |= ((Boolean) result);
}
}
}
return bResult;
}
public List<ZuulFilter> getFiltersByType(String filterType) {
List<ZuulFilter> list = hashFiltersByType.get(filterType);
if (list != null) return list;
list = new ArrayList<ZuulFilter>();
// 從FilterRegistry中擷取所有的ZuulFilter;在上面看到了所有的ZuulFilter都被添加到了FilterRegistry中
Collection<ZuulFilter> filters = filterRegistry.getAllFilters();
for (Iterator<ZuulFilter> iterator = filters.iterator(); iterator.hasNext(); ) {
ZuulFilter filter = iterator.next();
if (filter.filterType().equals(filterType)) {
list.add(filter);
}
}
Collections.sort(list); // sort by priority
hashFiltersByType.putIfAbsent(filterType, list);
return list;
}
}
以上就是Zuul網關的底層實作原理。
完畢!!!
求三連
Spring Cloud Function 快速入門
SpringCloud Hystrix實作資源隔離應用
SpringCloud Feign實作原理源分析
Spring Cloud 微服務日志收集管理Elastic Stack完整詳細版