赞
踩
生命周期方法(Lifecycle)
组件默认实现
:okHome //调用catalina.bat set "EXECUTABLE=%CATALINA_HOME%\bin\catalina.bat" rem Check that target executable exists if exist "%EXECUTABLE%" goto okExec echo Cannot find "%EXECUTABLE%" echo This file is needed to run this program goto end :okExec rem Get remaining unshifted command line arguments and save them in the set CMD_LINE_ARGS= :setArgs if ""%1""=="""" goto doneSetArgs set CMD_LINE_ARGS=%CMD_LINE_ARGS% %1 shift goto setArgs :doneSetArgs //执行 call "%EXECUTABLE%" start %CMD_LINE_ARGS% :end
if "%CLASSPATH%" == "" goto emptyClasspath
set "CLASSPATH=%CLASSPATH%;"
:emptyClasspath
set "CLASSPATH=%CLASSPATH%%CATALINA_HOME%\bin\bootstrap.jar"
org.apache.catalina.startup.Bootstrap#main
public static void main(String args[]) { synchronized (daemonLock) { //执行init方法初始化,创建Catalina对象 bootstrap.init(); //... String command = "start"; //... if (command.equals("startd")) { args[args.length - 1] = "start"; daemon.load(args); daemon.start(); } else if (command.equals("stopd")) { args[args.length - 1] = "stop"; daemon.stop(); } else if (command.equals("start")) { daemon.setAwait(true); daemon.load(args); daemon.start(); if (null == daemon.getServer()) { System.exit(1); } } else if (command.equals("stop")) { daemon.stopServer(args); } else if (command.equals("configtest")) { daemon.load(args); if (null == daemon.getServer()) { System.exit(1); } System.exit(0); } } }
解析配置xml :org.apache.catalina.startup.Catalina#parseServerXml
public void init() throws Exception { //初始化ClassLoader initClassLoaders(); Thread.currentThread().setContextClassLoader(catalinaLoader); SecurityClassLoad.securityClassLoad(catalinaLoader); //使用自定义ClassLoader类加载器 反射创建Catalina Class<?> startupClass = catalinaLoader.loadClass("org.apache.catalina.startup.Catalina"); Object startupInstance = startupClass.getConstructor().newInstance(); String methodName = "setParentClassLoader"; Class<?> paramTypes[] = new Class[1]; paramTypes[0] = Class.forName("java.lang.ClassLoader"); Object paramValues[] = new Object[1]; paramValues[0] = sharedLoader; //反射获取Catalina的setParentClassLoader Method method = startupInstance.getClass().getMethod(methodName, paramTypes); //设置父ClassLoader method.invoke(startupInstance, paramValues); catalinaDaemon = startupInstance; } 因为Bootstrap这个类在Tomcat打包发布时是放在bin\bootstrap.jar中, 而Catalina类是放在lib\catalina.jar中,两个jar是用不同的ClassLoader加载的, 所以不能在Bootstrap类中直接引用Catalina类,只能通过反射。
private void load(String[] arguments) throws Exception {
String methodName = "load";
//....
//获取Catalina的load方法
Method method = catalinaDaemon.getClass().getMethod(methodName, paramTypes);
//通过反射调用Catalina.load方法
method.invoke(catalinaDaemon, param);
}
public void load() { //执行初始化 initDirs(); initNaming(); //解析server.xml配置文件 parseServerXml(true); //创建Server Server s = getServer(); //初始化Server getServer().init(); } // 解析server.xml protected void parseServerXml(boolean start) { //.... try (ConfigurationSource.Resource resource = ConfigFileLoader.getSource().getServerXml()) { //创建启动或者停止的xml解析器Digester Digester digester = start ? createStartDigester() : createStopDigester(); //.... } catch (Exception e) { log.warn(sm.getString("catalina.configFail", file.getAbsolutePath()), e); if (file.exists() && !file.canRead()) { log.warn(sm.getString("catalina.incorrectPermissions")); } } }
public final synchronized void init() throws LifecycleException { if (!state.equals(LifecycleState.NEW)) { invalidTransition(Lifecycle.BEFORE_INIT_EVENT); } try { setStateInternal(LifecycleState.INITIALIZING, null, false); //调用抽象方法,执行具体实现,初始化 initInternal(); setStateInternal(LifecycleState.INITIALIZED, null, false); } catch (Throwable t) { handleSubClassException(t, "lifecycleBase.initFail", toString()); } } protected void initInternal() throws LifecycleException { super.initInternal(); //初始化 reconfigureUtilityExecutor(getUtilityThreadsInternal(utilityThreads)); register(utilityExecutor, "type=UtilityExecutor"); onameStringCache = register(new StringCache(), "type=StringCache"); // Register the MBeanFactory MBeanFactory factory = new MBeanFactory(); factory.setContainer(this); onameMBeanFactory = register(factory, "type=MBeanFactory"); globalNamingResources.init(); //循环初始化Service for (Service service : services) { service.init(); } }
protected void initInternal() throws LifecycleException { super.initInternal(); //初始化Engine引擎 if (engine != null) { engine.init(); } //初始化Executor线程池 for (Executor executor : findExecutors()) { if (executor instanceof JmxEnabled) { ((JmxEnabled) executor).setDomain(getDomain()); } executor.init(); } // 初始化监听器 mapperListener.init(); //初始化Connector连接器 synchronized (connectorsLock) { for (Connector connector : connectors) { connector.init(); } } }
protected void initInternal() throws LifecycleException {
// 初始化CoyoteAdapter
adapter = new CoyoteAdapter(this);
protocolHandler.setAdapter(adapter);
//....
//初始化ProtocolHandler
protocolHandler.init();
}
public void init() throws Exception {
//....
String endpointName = getName();
endpoint.setName(endpointName.substring(1, endpointName.length()-1));
endpoint.setDomain(domain);
//初始化EndPoint
endpoint.init();
}
public final void init() throws Exception { if (bindOnInit) { //绑定Servlet相关能力 bindWithCleanup(); bindState = BindState.BOUND_ON_INIT; } if (this.domain != null) { // 注册EndPoint oname = new ObjectName(domain + ":type=ThreadPool,name=\"" + getName() + "\""); Registry.getRegistry(null, null).registerComponent(this, oname, null); ObjectName socketPropertiesOname = new ObjectName(domain + ":type=SocketProperties,name=\"" + getName() + "\""); socketProperties.setObjectName(socketPropertiesOname); Registry.getRegistry(null, null).registerComponent(socketProperties, socketPropertiesOname, null); for (SSLHostConfig sslHostConfig : findSslHostConfigs()) { registerJmx(sslHostConfig); } } }
public void bind() throws Exception { //初始化ServerSocket initServerSocket(); setStopLatch(new CountDownLatch(1)); //初始化SSL initialiseSsl(); selectorPool.open(getName()); } //初始化ServerSocket protected void initServerSocket() throws Exception { if (!getUseInheritedChannel()) { serverSock = ServerSocketChannel.open(); socketProperties.setProperties(serverSock.socket()); InetSocketAddress addr = new InetSocketAddress(getAddress(), getPortWithOffset()); serverSock.socket().bind(addr,getAcceptCount()); } else { 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 }
public void start() throws Exception {
//如果没有初始化,则在此初始化
if (catalinaDaemon == null) {
init();
}
//反射调用Catalina的start方法
Method method = catalinaDaemon.getClass().getMethod("start", (Class [])null);
method.invoke(catalinaDaemon, (Object [])null);
}
public void start() { //启动Server try { getServer().start(); } catch (LifecycleException e) { try { //启动失败则销毁 getServer().destroy(); } catch (LifecycleException e1) { log.debug("destroy() failed for failed Server ", e1); } return; } if (generateCode) { // Generate loader which will load all generated classes generateLoader(); } // Register shutdown hook if (useShutdownHook) { if (shutdownHook == null) { shutdownHook = new CatalinaShutdownHook(); } Runtime.getRuntime().addShutdownHook(shutdownHook); LogManager logManager = LogManager.getLogManager(); if (logManager instanceof ClassLoaderLogManager) { ((ClassLoaderLogManager) logManager).setUseShutdownHook( false); } } if (await) { await(); stop(); } }
public final synchronized void start() throws LifecycleException { //.... setStateInternal(LifecycleState.STARTING_PREP, null, false); // startInternal(); } protected void startInternal() throws LifecycleException { //循环启动service synchronized (servicesLock) { for (Service service : services) { service.start(); } } if (periodicEventDelay > 0) { monitorFuture = getUtilityExecutor().scheduleWithFixedDelay( new Runnable() { @Override public void run() { startPeriodicLifecycleEvent(); } }, 0, 60, TimeUnit.SECONDS); } }
protected void startInternal() throws LifecycleException { // 启动Engine引擎 if (engine != null) { synchronized (engine) { engine.start(); } } //启动Executor线程连接池 synchronized (executors) { for (Executor executor: executors) { executor.start(); } } //启动监听器 mapperListener.start(); //启动Connector连接器 synchronized (connectorsLock) { for (Connector connector: connectors) { if (connector.getState() != LifecycleState.FAILED) { connector.start(); } } } }
protected void startInternal() throws LifecycleException {
//设置状态
setState(LifecycleState.STARTING);
//启动ProtocolHandler
protocolHandler.start();
}
public void start() throws Exception {
//启动Endpoint
endpoint.start();
monitorFuture = getUtilityExecutor().scheduleWithFixedDelay(
new Runnable() {
@Override
public void run() {
if (!isPaused()) {
startAsyncTimeout();
}
}
}, 0, 60, TimeUnit.SECONDS);
}
public final void start() throws Exception {
if (bindState == BindState.UNBOUND) {
bindWithCleanup();
bindState = BindState.BOUND_ON_START;
}
startInternal();
}
public void startInternal() throws Exception {
//初始化连接
initializeConnectionLatch();
//启动接收的线程
startAcceptorThread();
}
public class Acceptor<U> implements Runnable {
@Override
public void run() {
//接收客户端请求
socket = endpoint.serverSocketAccept();
}
}
//socket.accept监听接收客户端请求
protected SocketChannel serverSocketAccept() throws Exception {
return serverSock.accept();
}
参考资源: Java进阶教程Tomcat核心原理解析
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。