Zuul's working mechanism
Zuul in SpringBoot
一般情况我们在springboot工程中使用
@EnableZuulProxy
或者
@EnableZuulServer
Set up the application to act as a generic Zuul server without any built-in reverse proxy features
两个注解中一个来启动zuul网关
还有一些配置文件,这里先忽略
Being in EnableZuulServer
Take EnableZuulServer as an example to see how zuul works.
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(ZuulConfiguration.class)
public @interface EnableZuulServer {
}
ZuulConfiguration Class was imported in the EnableZuulServer annotation. Let's take a look at the ZuulConfiguration class.
@Configuration
@EnableConfigurationProperties({ ZuulProperties.class })
@ConditionalOnClass(ZuulServlet.class)
只有classpath中存在ZuulServlet类才生效。
// Make sure to get the ServerProperties from the same place as a normal web app would
@Import(ServerPropertiesAutoConfiguration.class)
public class ZuulConfiguration {
...
}
We see that the loading of the configuration file is defined in ZuulConfiguration, and we haven't seen where is the entrance of the runner zuul gateway? Continue to look down, a bean ZuulController is defined in ZuulConfiguration.
@Bean
public ZuulController zuulController() {
return new ZuulController();
}
The confusing name ZuulController, this is not our normal use of the Controller in the spring web framework. Let's look at the details:
public class ZuulController extends ServletWrappingController {
public ZuulController() {
setServletClass(ZuulServlet.class);
setServletName("zuul");
setSupportedMethods((String[]) null); // Allow all
}
...
}
ZuulController inherits ServletWrappingController, which originally wrapped ZuulServlet into a bean. by
public class ServletWrappingController extends AbstractController
implements BeanNameAware, InitializingBean, DisposableBean {
...
@Override
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 = this.servletClass.newInstance();
this.servletInstance.init(new DelegatingServletConfig());
}
...
}
Pass this.servletInstance.init(new DelegatingServletConfig());
to initialize ZuulServlet. When ZuulController processes a request, it is handled by super.handleRequestInternal(request, response);
ZuulServlet.
summary
The above briefly analyzes how springboot handles zuul. The source code path (the initialization of the parent class is not repeated here.):
EnableZuulServer --> ZuulConfiguration -->ZuulController--> ZuulServlet