介绍
该笔记是在学习拉勾教育 Java 高薪训练营后,结合课程和老师的视频,自己跟踪源码后做的笔记。
Bootstrap#load
使用反射调用 Catalina 实例的 load 方法,即 Catalina.load()。
private void load(String[] arguments) throws Exception {
// Call the load() method
String methodName = "load";
Object param[];
Class<?> paramTypes[];
if (arguments==null || arguments.length==0) {
paramTypes = null;
param = null;
} else {
paramTypes = new Class[1];
paramTypes[0] = arguments.getClass();
param = new Object[1];
param[0] = arguments;
}
// 根据方法名和参数获取 load 方法
Method method =
catalinaDaemon.getClass().getMethod(methodName, paramTypes);
if (log.isDebugEnabled()) {
log.debug("Calling startup class " + method);
}
// 调用 Catalina 实例的 load 方法,即 Catalina.load()
method.invoke(catalinaDaemon, param);
}
Catalina#load()
Tomcat 的 server.xml 结构如下,最外层结构是 Server,所以会先解析 Server,进行初始化。然后在由 Server 来调用其他组件的初始化,达到一键初始化的目的。
<Server>
<Service>
<Connector />
<Connector />
<Engine>
<Host>
<Context />
</Host>
</Engine>
</Service>
</Server>
- 创建解析器,用于解析 xml 配置文件,获取 conf/server.xml 文件的流;
- getServer().init(),获取 server,进行初始化,使用模板方法设计模式,调用的是 StandardServer#initInternal。
public void load() {
if (loaded) {
return;
}
loaded = true;
long t1 = System.nanoTime();
initDirs();
// Before digester - it may be needed
// 命名服务
initNaming();
// Create and execute our Digester
// 创建解析器,用于解析 xml 配置文件,比如解析 server.xml
Digester digester = createStartDigester();
InputSource inputSource = null;
InputStream inputStream = null;
File file = null;
try {
try {
// 获取 conf/server.xml 文件的流
file = configFile();
inputStream = new FileInputStream(file);
inputSource = new InputSource(file.toURI().toURL().toString());
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("catalina.configFail", file), e);
}
}
// ...
try {
inputSource.setByteStream(inputStream);
digester.push(this);
// 解析配置文件 conf/server.xml 的流
digester.parse(inputSource);
} catch (SAXParseException spe) {
log.warn("Catalina.start using " + getConfigFile() + ": " +
spe.getMessage());
return;
} catch (Exception e) {
log.warn("Catalina.start using " + getConfigFile() + ": " , e);
return;
}
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// Ignore
}
}
}
getServer().setCatalina(this);
getServer().setCatalinaHome(Bootstrap.getCatalinaHomeFile());
getServer().setCatalinaBase(Bootstrap.getCatalinaBaseFile());
// Stream redirection
initStreams();
// Start the new server
try {
// 获取 server,进行初始化,使用模板方法设计模式,调用的是 StandardServer#initInternal
getServer().init();
}
// ...
}
StandardServer#initInternal
遍历列表 services,调用 service.init() 方法,一个 Server 包含多个 Service。
private Service services[] = new Service[0];
@Override
protected void initInternal() throws LifecycleException {
super.initInternal();
// ...
// Initialize our defined Services
// 遍历 Service,调用其初始化方法,一个 Server 有多个 Service
for (int i = 0; i < services.length; i++) {
services[i].init();
}
}
StandardService#initInternal
调用多个组件 engine、executor、connector 等组件的 init() 方法。
private final Object connectorsLock = new Object();
@Override
protected void initInternal() throws LifecycleException {
super.initInternal();
if (engine != null) {
engine.init();
}
// Initialize any Executors
for (Executor executor : findExecutors()) {
if (executor instanceof JmxEnabled) {
((JmxEnabled) executor).setDomain(getDomain());
}
executor.init();
}
// Initialize mapper listener
mapperListener.init();
// Initialize our defined Connectors
// 遍历 connector 时,加锁
synchronized (connectorsLock) {
for (Connector connector : connectors) {
try {
connector.init();
} catch (Exception e) {
String message = sm.getString(
"standardService.connector.initFailed", connector);
log.error(message, e);
if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE"))
throw new LifecycleException(message);
}
}
}
}
StandardEngine#initInternal
调用父类 LifecycleMBeanBase 的 initInternal 方法。
@Override
protected void initInternal() throws LifecycleException {
// Ensure that a Realm is present before any attempt is made to start
// one. This will create the default NullRealm if necessary.
getRealm();
super.initInternal();
}
StandardThreadExecutor#initInternal
调用父类 LifecycleMBeanBase 的 initInternal 方法。
@Override
protected void initInternal() throws LifecycleException {
super.initInternal();
}
Connector#initInternal
设置适配器和进行端口绑定。
- CoyoteAdapter,适配器,用于将 Request 转换为 ServletRequest,this 为当前 connector;
- protocolHandler.init(),会调用 AbstractEndpoint 的 init() 方法,进行端口绑定。
@Override
protected void initInternal() throws LifecycleException {
super.initInternal();
// Initialize adapter
// 初始化适配器,用于将 Request 转换为 ServletRequest,this 为当前 connector
adapter = new CoyoteAdapter(this);
protocolHandler.setAdapter(adapter);
// ...
try {
protocolHandler.init();
} catch (Exception e) {
throw new LifecycleException(
sm.getString("coyoteConnector.protocolHandlerInitializationFailed"), e);
}
}
AbstractProtocol#init
主要为调用 AbstractEndpoint 的 init() 方法,进行端口绑定。
@Override
public void init() throws Exception {
// ...
String endpointName = getName();
endpoint.setName(endpointName.substring(1, endpointName.length()-1));
endpoint.setDomain(domain);
endpoint.init();
}
AbstractEndpoint#init
核心方法为 bind(),进行端口绑定。
public void init() throws Exception {
if (bindOnInit) {
// 端口绑定,默认为 NioEndPoint
bind();
bindState = BindState.BOUND_ON_INIT;
}
// ...
}
NioEndPoint#bind
- ServerSocketChannel.open(),调用底层 NIO 的 api,获取服务端的 Socket,进行端口绑定;
- selectorPool.open(),用于接收客户端的连接。
@Override
public void bind() throws Exception {
if (!getUseInheritedChannel()) {
// 调用底层 NIO 的 api,获取服务端的 Socket
serverSock = ServerSocketChannel.open();
socketProperties.setProperties(serverSock.socket());
// 根据 IP 和端口构造地址
InetSocketAddress addr = (getAddress()!=null?new InetSocketAddress(getAddress(),getPort()):new InetSocketAddress(getPort()));
// 绑定端口,比如 8080
serverSock.socket().bind(addr,getAcceptCount());
} else {
// Retrieve the channel provided by the OS
Channel ic = System.inheritedChannel();
if (ic instanceof ServerSocketChannel) {
serverSock = (ServerSocketChannel) ic;
}
if (serverSock == null) {
throw new IllegalArgumentException(sm.getString("endpoint.init.bind.inherited"));
}
}
serverSock.configureBlocking(true); //mimic APR behavior
// ...
// 用于接收客户端的连接
selectorPool.open();
}
NioSelectorPool#open
接收客户端的连接。
public void open() throws IOException {
enabled = true;
getSharedSelector();
if (SHARED) {
blockingSelector = new NioBlockingSelector();
blockingSelector.open(getSharedSelector());
}
}