最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Tomcat Server的設(shè)計和實現(xiàn):StandardServer詳解

 更新時間:2026年04月28日 08:57:00   作者:程序員Seven  
文章主要介紹了Tomcat中StandardServer的整體類依賴結(jié)構(gòu),通過解析server.xml文件來理解Server的相關(guān)配置屬性及其作用,感興趣的朋友跟隨小編一起看看吧

理解思路

  • 第一:抓住StandardServer整體類依賴結(jié)構(gòu)來理解

  • 第二:結(jié)合server.xml來理解

見下文具體闡述。

  • 第三:結(jié)合Server Config官方配置文檔

http://tomcat.apache.org/tomcat-9.0-doc/config/server.html

Server結(jié)構(gòu)設(shè)計

我們需要從高一點的維度去理解Server的結(jié)構(gòu)設(shè)計,而不是多少方法多少代碼;這里的理解一定是要結(jié)合Server.xml對應(yīng)理解。

server.xml

  • 首先要看下server.xml,這樣你便知道了需要了解的四個部分
<Server port="8005" shutdown="SHUTDOWN">
  <!-- 1.屬性說明
    port:指定一個端口,這個端口負(fù)責(zé)監(jiān)聽關(guān)閉Tomcat的請求
    shutdown:向以上端口發(fā)送的關(guān)閉服務(wù)器的命令字符串
  -->
  <!-- 2.Listener 相關(guān) -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" />
  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.storeconfig.StoreConfigLifecycleListener"/>
  <!-- 3.GlobalNamingResources 相關(guān) -->
  <GlobalNamingResources>
    <Environment name="simpleValue" type="java.lang.Integer" value="30"/>
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
       description="User database that can be updated and saved"
           factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
          pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>
  <!-- 4.service 相關(guān) -->
  <Service name="Catalina">
  </Service>
</Server>

Server中的接口設(shè)計

  • 公共屬性, 包括上面的port,shutdown, address等
/**
  * @return the port number we listen to for shutdown commands.
  *
  * @see #getPortOffset()
  * @see #getPortWithOffset()
  */
public int getPort();
/**
  * Set the port number we listen to for shutdown commands.
  *
  * @param port The new port number
  *
  * @see #setPortOffset(int)
  */
public void setPort(int port);
/**
  * Get the number that offsets the port used for shutdown commands.
  * For example, if port is 8005, and portOffset is 1000,
  * the server listens at 9005.
  *
  * @return the port offset
  */
public int getPortOffset();
/**
  * Set the number that offsets the server port used for shutdown commands.
  * For example, if port is 8005, and you set portOffset to 1000,
  * connector listens at 9005.
  *
  * @param portOffset sets the port offset
  */
public void setPortOffset(int portOffset);
/**
  * Get the actual port on which server is listening for the shutdown commands.
  * If you do not set port offset, port is returned. If you set
  * port offset, port offset + port is returned.
  *
  * @return the port with offset
  */
public int getPortWithOffset();
/**
  * @return the address on which we listen to for shutdown commands.
  */
public String getAddress();
/**
  * Set the address on which we listen to for shutdown commands.
  *
  * @param address The new address
  */
public void setAddress(String address);
/**
  * @return the shutdown command string we are waiting for.
  */
public String getShutdown();
/**
  * Set the shutdown command we are waiting for.
  *
  * @param shutdown The new shutdown command
  */
public void setShutdown(String shutdown);
/**
  * Get the utility thread count.
  * @return the thread count
  */
public int getUtilityThreads();
/**
  * Set the utility thread count.
  * @param utilityThreads the new thread count
  */
public void setUtilityThreads(int utilityThreads);
屬性描述
className使用的Java類名稱。此類必須實現(xiàn)org.apache.catalina.Server接口。如果未指定類名,則將使用標(biāo)準(zhǔn)實現(xiàn)。
address該服務(wù)器等待關(guān)閉命令的TCP / IP地址。如果未指定地址,localhost則使用。
port該服務(wù)器等待關(guān)閉命令的TCP / IP端口號。設(shè)置為-1禁用關(guān)閉端口。注意:當(dāng)使用Apache Commons Daemon啟動Tomcat (在Windows上作為服務(wù)運行,或者在un * xes上使用jsvc運行)時,禁用關(guān)閉端口非常有效。但是,當(dāng)使用標(biāo)準(zhǔn)shell腳本運行Tomcat時,不能使用它,因為它將阻止shutdown.bat
portOffset應(yīng)用于port和嵌套到任何嵌套連接器的端口的偏移量。它必須是一個非負(fù)整數(shù)。如果未指定,0則使用默認(rèn)值。
shutdown為了關(guān)閉Tomcat,必須通過與指定端口號的TCP / IP連接接收的命令字符串。
utilityThreads此service中用于各種實用程序任務(wù)(包括重復(fù)執(zhí)行的線程)的線程數(shù)。特殊值0將導(dǎo)致使用該值 Runtime.getRuntime().availableProcessors()。Runtime.getRuntime().availableProcessors() + value除非小于1,否則將使用負(fù)值, 在這種情況下將使用1個線程。預(yù)設(shè)值是1。
  • NamingResources
/**
  * @return the global naming resources.
  */
public NamingResourcesImpl getGlobalNamingResources();
/**
  * Set the global naming resources.
  *
  * @param globalNamingResources The new global naming resources
  */
public void setGlobalNamingResources
    (NamingResourcesImpl globalNamingResources);
/**
  * @return the global naming resources context.
  */
public javax.naming.Context getGlobalNamingContext();
  • Service相關(guān), 包括添加Service, 查找Service,刪除service等
/**
  * Add a new Service to the set of defined Services.
  *
  * @param service The Service to be added
  */
public void addService(Service service);
/**
  * Wait until a proper shutdown command is received, then return.
  */
public void await();
/**
  * Find the specified Service
  *
  * @param name Name of the Service to be returned
  * @return the specified Service, or <code>null</code> if none exists.
  */
public Service findService(String name);
/**
  * @return the set of Services defined within this Server.
  */
public Service[] findServices();
/**
  * Remove the specified Service from the set associated from this
  * Server.
  *
  * @param service The Service to be removed
  */
public void removeService(Service service);

StandardServer的實現(xiàn)

線程池

// 此service中用于各種實用程序任務(wù)(包括重復(fù)執(zhí)行的線程)的線程數(shù)
@Override
public int getUtilityThreads() {
    return utilityThreads;
}
/**
  * 獲取內(nèi)部進程數(shù)計算邏輯:
  * > 0時,即utilityThreads的值。
  * <=0時,Runtime.getRuntime().availableProcessors() + result...
  */
private static int getUtilityThreadsInternal(int utilityThreads) {
    int result = utilityThreads;
    if (result <= 0) {
        result = Runtime.getRuntime().availableProcessors() + result;
        if (result < 2) {
            result = 2;
        }
    }
    return result;
}
@Override
public void setUtilityThreads(int utilityThreads) {
    // Use local copies to ensure thread safety
    int oldUtilityThreads = this.utilityThreads;
    if (getUtilityThreadsInternal(utilityThreads) < getUtilityThreadsInternal(oldUtilityThreads)) {
        return;
    }
    this.utilityThreads = utilityThreads;
    if (oldUtilityThreads != utilityThreads && utilityExecutor != null) {
        reconfigureUtilityExecutor(getUtilityThreadsInternal(utilityThreads));
    }
}
// 線程池
private synchronized void reconfigureUtilityExecutor(int threads) {
    // The ScheduledThreadPoolExecutor doesn't use MaximumPoolSize, only CorePoolSize is available
    if (utilityExecutor != null) {
        utilityExecutor.setCorePoolSize(threads);
    } else {
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor =
                new ScheduledThreadPoolExecutor(threads,
                        new TaskThreadFactory("Catalina-utility-", utilityThreadsAsDaemon, Thread.MIN_PRIORITY));
        scheduledThreadPoolExecutor.setKeepAliveTime(10, TimeUnit.SECONDS);
        scheduledThreadPoolExecutor.setRemoveOnCancelPolicy(true);
        scheduledThreadPoolExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
        utilityExecutor = scheduledThreadPoolExecutor;
        utilityExecutorWrapper = new org.apache.tomcat.util.threads.ScheduledThreadPoolExecutor(utilityExecutor);
    }
}
/**
  * Get if the utility threads are daemon threads.
  * @return the threads daemon flag
  */
public boolean getUtilityThreadsAsDaemon() {
    return utilityThreadsAsDaemon;
}
/**
  * Set the utility threads daemon flag. The default value is true.
  * @param utilityThreadsAsDaemon the new thread daemon flag
  */
public void setUtilityThreadsAsDaemon(boolean utilityThreadsAsDaemon) {
    this.utilityThreadsAsDaemon = utilityThreadsAsDaemon;
}

Service相關(guān)方法實現(xiàn)

里面的方法都很簡單。

/**
  * Add a new Service to the set of defined Services.
  *
  * @param service The Service to be added
  */
@Override
public void addService(Service service) {
    service.setServer(this);
    synchronized (servicesLock) {
        Service results[] = new Service[services.length + 1];
        System.arraycopy(services, 0, results, 0, services.length);
        results[services.length] = service;
        services = results;
        if (getState().isAvailable()) {
            try {
                service.start();
            } catch (LifecycleException e) {
                // Ignore
            }
        }
        // Report this property change to interested listeners
        support.firePropertyChange("service", null, service);
    }
}
public void stopAwait() {
    stopAwait=true;
    Thread t = awaitThread;
    if (t != null) {
        ServerSocket s = awaitSocket;
        if (s != null) {
            awaitSocket = null;
            try {
                s.close();
            } catch (IOException e) {
                // Ignored
            }
        }
        t.interrupt();
        try {
            t.join(1000);
        } catch (InterruptedException e) {
            // Ignored
        }
    }
}
/**
  * Wait until a proper shutdown command is received, then return.
  * This keeps the main thread alive - the thread pool listening for http
  * connections is daemon threads.
  */
@Override
public void await() {
    // Negative values - don't wait on port - tomcat is embedded or we just don't like ports
    if (getPortWithOffset() == -2) {
        // undocumented yet - for embedding apps that are around, alive.
        return;
    }
    if (getPortWithOffset() == -1) {
        try {
            awaitThread = Thread.currentThread();
            while(!stopAwait) {
                try {
                    Thread.sleep( 10000 );
                } catch( InterruptedException ex ) {
                    // continue and check the flag
                }
            }
        } finally {
            awaitThread = null;
        }
        return;
    }
    // Set up a server socket to wait on
    try {
        awaitSocket = new ServerSocket(getPortWithOffset(), 1,
                InetAddress.getByName(address));
    } catch (IOException e) {
        log.error(sm.getString("standardServer.awaitSocket.fail", address,
                String.valueOf(getPortWithOffset()), String.valueOf(getPort()),
                String.valueOf(getPortOffset())), e);
        return;
    }
    try {
        awaitThread = Thread.currentThread();
        // Loop waiting for a connection and a valid command
        while (!stopAwait) {
            ServerSocket serverSocket = awaitSocket;
            if (serverSocket == null) {
                break;
            }
            // Wait for the next connection
            Socket socket = null;
            StringBuilder command = new StringBuilder();
            try {
                InputStream stream;
                long acceptStartTime = System.currentTimeMillis();
                try {
                    socket = serverSocket.accept();
                    socket.setSoTimeout(10 * 1000);  // Ten seconds
                    stream = socket.getInputStream();
                } catch (SocketTimeoutException ste) {
                    // This should never happen but bug 56684 suggests that
                    // it does.
                    log.warn(sm.getString("standardServer.accept.timeout",
                            Long.valueOf(System.currentTimeMillis() - acceptStartTime)), ste);
                    continue;
                } catch (AccessControlException ace) {
                    log.warn(sm.getString("standardServer.accept.security"), ace);
                    continue;
                } catch (IOException e) {
                    if (stopAwait) {
                        // Wait was aborted with socket.close()
                        break;
                    }
                    log.error(sm.getString("standardServer.accept.error"), e);
                    break;
                }
                // Read a set of characters from the socket
                int expected = 1024; // Cut off to avoid DoS attack
                while (expected < shutdown.length()) {
                    if (random == null)
                        random = new Random();
                    expected += (random.nextInt() % 1024);
                }
                while (expected > 0) {
                    int ch = -1;
                    try {
                        ch = stream.read();
                    } catch (IOException e) {
                        log.warn(sm.getString("standardServer.accept.readError"), e);
                        ch = -1;
                    }
                    // Control character or EOF (-1) terminates loop
                    if (ch < 32 || ch == 127) {
                        break;
                    }
                    command.append((char) ch);
                    expected--;
                }
            } finally {
                // Close the socket now that we are done with it
                try {
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException e) {
                    // Ignore
                }
            }
            // Match against our command string
            boolean match = command.toString().equals(shutdown);
            if (match) {
                log.info(sm.getString("standardServer.shutdownViaPort"));
                break;
            } else
                log.warn(sm.getString("standardServer.invalidShutdownCommand", command.toString()));
        }
    } finally {
        ServerSocket serverSocket = awaitSocket;
        awaitThread = null;
        awaitSocket = null;
        // Close the server socket and return
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }
}
/**
  * @return the specified Service (if it exists); otherwise return
  * <code>null</code>.
  *
  * @param name Name of the Service to be returned
  */
@Override
public Service findService(String name) {
    if (name == null) {
        return null;
    }
    synchronized (servicesLock) {
        for (Service service : services) {
            if (name.equals(service.getName())) {
                return service;
            }
        }
    }
    return null;
}
/**
  * @return the set of Services defined within this Server.
  */
@Override
public Service[] findServices() {
    return services;
}
/**
  * @return the JMX service names.
  */
public ObjectName[] getServiceNames() {
    ObjectName onames[]=new ObjectName[ services.length ];
    for( int i=0; i<services.length; i++ ) {
        onames[i]=((StandardService)services[i]).getObjectName();
    }
    return onames;
}
/**
  * Remove the specified Service from the set associated from this
  * Server.
  *
  * @param service The Service to be removed
  */
@Override
public void removeService(Service service) {
    synchronized (servicesLock) {
        int j = -1;
        for (int i = 0; i < services.length; i++) {
            if (service == services[i]) {
                j = i;
                break;
            }
        }
        if (j < 0)
            return;
        try {
            services[j].stop();
        } catch (LifecycleException e) {
            // Ignore
        }
        int k = 0;
        Service results[] = new Service[services.length - 1];
        for (int i = 0; i < services.length; i++) {
            if (i != j)
                results[k++] = services[i];
        }
        services = results;
        // Report this property change to interested listeners
        support.firePropertyChange("service", service, null);
    }
}

Lifecycle相關(guān)模板方法

這里只展示startInternal方法

/**
 * Start nested components ({@link Service}s) and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected void startInternal() throws LifecycleException {
    fireLifecycleEvent(CONFIGURE_START_EVENT, null);
    setState(LifecycleState.STARTING);
    globalNamingResources.start();
    // Start our defined Services
    synchronized (servicesLock) {
        for (int i = 0; i < services.length; i++) {
            services[i].start();
        }
    }
    if (periodicEventDelay > 0) {
        monitorFuture = getUtilityExecutor().scheduleWithFixedDelay(
                new Runnable() {
                    @Override
                    public void run() {
                        startPeriodicLifecycleEvent();
                    }
                }, 0, 60, TimeUnit.SECONDS);
    }
}
protected void startPeriodicLifecycleEvent() {
    if (periodicLifecycleEventFuture == null || (periodicLifecycleEventFuture != null && periodicLifecycleEventFuture.isDone())) {
        if (periodicLifecycleEventFuture != null && periodicLifecycleEventFuture.isDone()) {
            // There was an error executing the scheduled task, get it and log it
            try {
                periodicLifecycleEventFuture.get();
            } catch (InterruptedException | ExecutionException e) {
                log.error(sm.getString("standardServer.periodicEventError"), e);
            }
        }
        periodicLifecycleEventFuture = getUtilityExecutor().scheduleAtFixedRate(
                new Runnable() {
                    @Override
                    public void run() {
                        fireLifecycleEvent(Lifecycle.PERIODIC_EVENT, null);
                    }
                }, periodicEventDelay, periodicEventDelay, TimeUnit.SECONDS);
    }
}

方法的第一行代碼先觸發(fā) CONFIGURE_START_EVENT 事件,以便執(zhí)行 StandardServer 的 LifecycleListener 監(jiān)聽器,然后調(diào)用 setState 方法設(shè)置成 LifecycleBase 的 state 屬性為 LifecycleState.STARTING。 接著就 globalNamingResources.start(),跟 initInternal 方法其實是類似的。

再接著就調(diào)用 Service 的 start 方法來啟動 Service 組件??梢钥闯?,StandardServe 的 startInternal 跟 initInternal 方法類似,都是調(diào)用內(nèi)部的 service 組件的相關(guān)方法。

調(diào)用完 service.init 方法后,就使用 getUtilityExecutor() 返回的線程池延遲執(zhí)行startPeriodicLifecycleEvent 方法,而在 startPeriodicLifecycleEvent 方法里,也是使用 getUtilityExecutor() 方法,定期執(zhí)行 fireLifecycleEvent 方法,處理 Lifecycle.PERIODIC_EVENT 事件,如果有需要定期處理的,可以再 Server 的 LifecycleListener 里處理 Lifecycle.PERIODIC_EVENT 事件。

到此這篇關(guān)于Tomcat Server的設(shè)計和實現(xiàn):StandardServer詳解的文章就介紹到這了,更多相關(guān)Tomcat Server StandardServer內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Tomcat里catalina.sh的使用小結(jié)

    Tomcat里catalina.sh的使用小結(jié)

    在Tomcat中,catalina.sh或 catalina.bat是用于控制 Tomcat服務(wù)器的運行,負(fù)責(zé)設(shè)置環(huán)境變量、啟動/關(guān)閉 JVM 進程,并傳遞參數(shù)給 Tomcat 的核心組件,下面就來介紹一下如何使用
    2026-02-02
  • 解決啟動tomcat報錯發(fā)生服務(wù)特定錯誤1的問題

    解決啟動tomcat報錯發(fā)生服務(wù)特定錯誤1的問題

    這篇文章主要介紹了解決啟動tomcat報錯發(fā)生服務(wù)特定錯誤1的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • Tomcat之配置文件的具體使用

    Tomcat之配置文件的具體使用

    Tomcat服務(wù)器的配置文件主要在conf文件夾中,本文就詳細(xì)的來介紹一下Tomcat之配置文件的具體使用,具有一定參考價值,感興趣的可以了解一下
    2023-10-10
  • Tomcat服務(wù)器入門超詳細(xì)教程

    Tomcat服務(wù)器入門超詳細(xì)教程

    Tomcat 服務(wù)器是一個免費的開放源代碼的Web 應(yīng)用服務(wù)器,屬于輕量級應(yīng)用服務(wù)器,在中小型系統(tǒng)和并發(fā)訪問用戶不是很多的場合下被普遍使用,是開發(fā)和調(diào)試JSP 程序的首選,這篇文章主要介紹了Tomcat服務(wù)器入門超詳細(xì)教程,需要的朋友可以參考下
    2021-11-11
  • IDEA2022創(chuàng)建Web項目配置Tomcat的詳細(xì)圖文說明

    IDEA2022創(chuàng)建Web項目配置Tomcat的詳細(xì)圖文說明

    因為學(xué)習(xí)JavaEE需要配置Tomcat,所以抽出時間對IDEA進行配置與創(chuàng)建,下面這篇文章主要給大家介紹了關(guān)于IDEA2022創(chuàng)建Web項目配置Tomcat的詳細(xì)圖文說明,需要的朋友可以參考下
    2023-04-04
  • Tomcat 7-dbcp配置數(shù)據(jù)庫連接池詳解

    Tomcat 7-dbcp配置數(shù)據(jù)庫連接池詳解

    這篇文章主要介紹了Tomcat 7-dbcp配置數(shù)據(jù)庫連接池詳解的相關(guān)資料,需要的朋友可以參考下
    2017-04-04
  • 解決tomcat部署時war和war exploded導(dǎo)致的問題

    解決tomcat部署時war和war exploded導(dǎo)致的問題

    war包和warexploded模式的區(qū)別主要在于部署方式,war包是在項目發(fā)布時打包上傳,而warexploded模式則是直接將文件夾結(jié)構(gòu)上傳到服務(wù)器,支持熱部署,常用于開發(fā)階段,這種差異可能導(dǎo)致樣式和文件引用問題,如在不同電腦部署時路徑設(shè)置的不同
    2024-10-10
  • Nginx/Httpd反代tomcat配置教程

    Nginx/Httpd反代tomcat配置教程

    這篇文章主要介紹了Nginx/Httpd反代tomcat配置教程以及一些常見的反代服務(wù)器,本文通過圖文的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-07-07
  • Tomcat配置訪問日志和線程數(shù)的實現(xiàn)步驟

    Tomcat配置訪問日志和線程數(shù)的實現(xiàn)步驟

    本文主要介紹了Tomcat配置訪問日志和線程數(shù)的實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-05-05
  • 使用Maven tomcat:run命令啟動web項目時修改默認(rèn)端口的方法

    使用Maven tomcat:run命令啟動web項目時修改默認(rèn)端口的方法

    今天小編就為大家分享一篇使用Maven tomcat:run命令啟動web項目時修改默認(rèn)端口的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-05-05

最新評論

滨州市| 崇信县| 南乐县| 邢台县| 梅河口市| 平远县| 元朗区| 策勒县| 巢湖市| 广水市| 太和县| 黔西| 嘉鱼县| 峨山| 巢湖市| 嘉黎县| 东平县| 嘉峪关市| 田林县| 阜城县| 威信县| 老河口市| 常熟市| 江门市| 鄯善县| 天峨县| 大姚县| 厦门市| 邢台县| 木兰县| 望奎县| 商城县| 紫金县| 阳新县| 武夷山市| 海南省| 青神县| 南丹县| 桂平市| 招远市| 大冶市|