SpringBoot使用Undertow代替Tomcat


 

  在SpringBoot框架中,我們使用最多的是Tomcat,這是SpringBoot默認的容器技術,而且是內嵌式的Tomcat。

  同時,SpringBoot也支持Undertow容器,Undertow 是基於java nio的web服務器,應用比較廣泛,內置提供的PathResourceManager,可以用來直接訪問文件系統;如果你有文件需要對外提供訪問,除了ftp,nginx等,undertow 也是一個不錯的選擇,作為java開發,服務搭建非常簡便。我們可以很方便的用Undertow替換Tomcat,而Undertow的性能和內存使用方面都優於Tomcat,那我們如何使用Undertow技術呢?

 

1. 配置Undertow

  Spring boot內嵌容器默認為Tomcat,想要換成Undertow,非常容易,只需修改spring-boot-starter-web依賴,移除tomcat的依賴:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

  然后,添加undertow依賴:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>

  這樣即可,使用默認參數啟動undertow服務器。如果需要修改undertow參數,繼續往下看。

  undertow的參數設置:

server:  
    port: 8084  
    http2:  
        enabled: true  
    undertow:  
        io-threads: 16  
        worker-threads: 256  
        buffer-size: 1024  
        buffers-per-region: 1024  
        direct-buffers: true 

  io-threads:IO線程數, 它主要執行非阻塞的任務,它們會負責多個連接,默認設置每個CPU核心一個線程,不可設置過大,否則啟動項目會報錯:打開文件數過多。

  worker-threads:阻塞任務線程池,當執行類似servlet請求阻塞IO操作,undertow會從這個線程池中取得線程。它的值取決於系統線程執行任務的阻塞系數,默認值是 io-threads*8

  以下配置會影響buffer,這些buffer會用於服務器連接的IO操作,有點類似netty的池化內存管理。

  buffer-size:每塊buffer的空間大小,越小的空間被利用越充分,不要設置太大,以免影響其他應用,合適即可

  buffers-per-region:每個區分配的buffer數量,所以pool的大小是buffer-size * buffers-per-region

  direct-buffers:是否分配的直接內存(NIO直接分配的堆外內存)

 

2. 啟動SpringBoot測試

  Undertow啟動成功提示語:[INFO ] 2020-08-13 10:38:32 [main] o.s.b.w.e.u.UndertowServletWebServer - Undertow started on port(s) 80 (http) with context path ''

  Tomcat啟動成功提示語:    [INFO ] 2020-08-13 10:41:35 [main] o.s.b.w.e.tomcat.TomcatWebServer - Tomcat started on port(s): 80 (http) with context path ''

 

3. Undertow的FileServer

import java.io.File;

import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.server.handlers.resource.PathResourceManager;

public class FileServer {
    public static void main(String[] args) {
        File file = new File("/");
        Undertow server = Undertow.builder().addHttpListener(8080, "localhost")
                .setHandler(Handlers.resource(new PathResourceManager(file.toPath(), 100))
                        .setDirectoryListingEnabled(true))
                .build();
        server.start();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM