手寫一個基於NIO的迷你版Tomcat

筆者也建立的自己的公衆號啦,平時會分享一些編程知識,歡迎各位大佬支持~

掃碼或微信搜索北風IT之路關注

本文公衆號地址:手寫一個基於NIO的迷你版Tomcat

在很久之前看到了一篇文章寫一個迷你版的Tomcat,覺得還是很有意思的,於是也跟着手敲了一遍,果不其然得出了想要的hello world,但是他這個是基於BIO的,正好最近看了併發編程的書,於是嘗試將這位大佬的代碼改一改,於是就有了這個基於NIO的迷你Tomcat。

源代碼已更新至我的Github:https://github.com/tzfun/MyTomcat

BIO和NIO

BIO是同步阻塞IO,在實際場景中大部分時間消耗在了IO等待上了,比較消耗資源,所以這種IO方式逐漸被替代了,具體介紹這裏不再贅述。取而代之的是NIO(New IO),它是一種同步非阻塞式的IO,它通過Selector自旋式或回調式的方式去處理準備好數據的Channel,Channel即通道,相當於BIO中的流,它不存在花費大量時間去IO等待,從而大大提升了吞吐量。Tomcat在老版本也是基於BIO的,後續版本更新也全部替換爲NIO。

項目結構

項目結構和原作者的結構幾乎一樣,只是代碼實現不一樣,具體結構看下圖:

Request和Response

Tomcat主要是Http服務,所以處理的協議是Http協議,那麼Http的頭部信息由請求行、請求頭部、空行、請求數據組成,只需要拆分這些數據即可處理http請求,這裏我只是簡單的處理了一下,其他詳細內容看註釋。

Request

package mytomcat;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.HashMap;

/**
 * @author beifengtz
 * <a href='http://www.beifengtz.com'>www.beifengtz.com</a>
 * <p>location: mytomcat.javase_learning</p>
 * Created in 14:45 2019/4/21
 */
public class MyRequest {
    private String url;
    private String method;
    private HashMap<String,String> param = new HashMap<>();

    public MyRequest(SelectionKey selectionKey) throws IOException{
        //  從契約獲取通道
        SocketChannel channel = (SocketChannel) selectionKey.channel();

        String httpRequest = "";
        ByteBuffer bb = ByteBuffer.allocate(16*1024);   //  從堆內存中獲取內存
        int length = 0; //  讀取byte數組的長度
        length = channel.read(bb);  //  從通道中讀取數據到ByteBuffer容器中
        if (length < 0){
            selectionKey.cancel();  //  取消該契約
        }else {
            httpRequest = new String(bb.array()).trim();    //  將ByteBuffer轉爲String
            String httpHead = httpRequest.split("\n")[0];   //  獲取請求頭
            url = httpHead.split("\\s")[1].split("\\?")[0]; //  獲取請求路徑
            String path = httpHead.split("\\s")[1]; //  請求全路徑,包含get的參數數據
            method = httpHead.split("\\s")[0];

            //  一下是拆分get請求的參數數據
            String[] params = path.indexOf("?") > 0 ? path.split("\\?")[1].split("\\&") : null;
            if (params != null){
                try{
                    for (String tmp : params){
                        param.put(tmp.split("\\=")[0],tmp.split("\\=")[1]);
                    }
                }catch (NullPointerException e){
                    e.printStackTrace();
                }
            }
            System.out.println(this);
        }
        bb.flip();
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    @Override
    public String toString() {
        return "MyRequest{" +
                "url='" + url + '\'' +
                ", method='" + method + '\'' +
                ", param=" + param +
                '}';
    }
}

Response

package mytomcat;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author beifengtz
 * <a href='http://www.beifengtz.com'>www.beifengtz.com</a>
 * <p>location: mytomcat.javase_learning</p>
 * Created in 14:49 2019/4/21
 */
public class MyResponse {
    private SelectionKey selectionKey;

    public MyResponse(SelectionKey selectionKey){
        this.selectionKey = selectionKey;
    }

    public void write(String content) throws IOException{
        //  拼接相應數據包
        StringBuffer httpResponse = new StringBuffer();
        httpResponse.append("HTTP/1.1 200 OK\n")
                .append("Content-type:text/html\n")
                .append("\r\n")
                .append("<html><body>")
                .append(content)
                .append("</body></html>");
        
        // 轉換爲ByteBuffer
        ByteBuffer bb = ByteBuffer.wrap(httpResponse.toString().getBytes(StandardCharsets.UTF_8));
        SocketChannel channel = (SocketChannel) selectionKey.channel(); //  從契約獲取通道
        long len = channel.write(bb);   //  向通道中寫入數據
        if (len == -1){
            selectionKey.cancel();
        }
        bb.flip();
        channel.close();
        selectionKey.cancel();
    }
}

Servlet和Mapping映射類及其配置類

在Java web開發中都會遇到Servlet和Mapping的配置,這些是必備的元素,Servlet負責定義處理請求和響應的方法,它是一個抽象類。

Servlet

package mytomcat;

/**
 * @author beifengtz
 * <a href='http://www.beifengtz.com'>www.beifengtz.com</a>
 * <p>location: mytomcat.javase_learning</p>
 * Created in 14:53 2019/4/21
 */
public abstract class MyServlet {

    public abstract void doGet(MyRequest myRequest,MyResponse myResponse);

    public abstract void doPost(MyRequest myRequest,MyResponse myResponse);

    public void service(MyRequest myRequest,MyResponse myResponse){
        if (myRequest.getMethod().equalsIgnoreCase("POST")){
            doPost(myRequest,myResponse);
        }else if (myRequest.getMethod().equalsIgnoreCase("GET")){
            doGet(myRequest,myResponse);
        }
    }
}

Mapping映射是負責將某些請求路徑分發到各自處理類進行處理,那麼就需要一個配置類,以下是ServletMapping類的定義和Config類。

ServletMapping

package mytomcat;

/**
 * @author beifengtz
 * <a href='http://www.beifengtz.com'>www.beifengtz.com</a>
 * <p>location: mytomcat.javase_learning</p>
 * Created in 14:59 2019/4/21
 */
public class ServletMapping {
    private String servletName;
    private String url;
    private String clazz;

    public ServletMapping(String servletName, String url, String clazz) {
        this.servletName = servletName;
        this.url = url;
        this.clazz = clazz;
    }

    public String getServletName() {
        return servletName;
    }

    public void setServletName(String servletName) {
        this.servletName = servletName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getClazz() {
        return clazz;
    }

    public void setClazz(String clazz) {
        this.clazz = clazz;
    }
}

ServletMappingConfig

package mytomcat;

import java.util.ArrayList;
import java.util.List;

/**
 * @author beifengtz
 * <a href='http://www.beifengtz.com'>www.beifengtz.com</a>
 * <p>location: mytomcat.javase_learning</p>
 * Created in 15:01 2019/4/21
 */
public class ServletMappingConfig {
    public static List<ServletMapping> servletMappingList = new ArrayList<>();

    static {
        servletMappingList.add(new ServletMapping("helloWorld","/world","mytomcat.HelloWorldServlet"));
    }
}

當然一般這個配置是通過xml文件去配置的。

下面是處理/world請求的處理類

package mytomcat;

import java.io.IOException;

/**
 * @author beifengtz
 * <a href='http://www.beifengtz.com'>www.beifengtz.com</a>
 * <p>location: mytomcat.javase_learning</p>
 * Created in 14:57 2019/4/21
 */
public class HelloWorldServlet extends MyServlet {
    @Override
    public void doGet(MyRequest myRequest, MyResponse myResponse) {
        try{
            myResponse.write("get hello world");
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @Override
    public void doPost(MyRequest myRequest, MyResponse myResponse) {
        try{
            myResponse.write("post hello world");
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

Tomcat核心啓動類

Tomcat的啓動類是它的核心,其中包含初始化Mapping、監聽端口、處理請求和響應等,我與原作者的主要區別也就是在這一部分,用NIO替換了BIO的接收數據模式,採用線程池處理數據。

MyTomcat

package mytomcat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author beifengtz
 * <a href='http://www.beifengtz.com'>www.beifengtz.com</a>
 * <p>location: mytomcat.javase_learning</p>
 * Created in 15:03 2019/4/21
 */
public class MyTomcat {
    private int port = 8080;
    private Map<String, String> urlServletMap = new HashMap<>();

    private Selector selector;
    private ExecutorService es = Executors.newCachedThreadPool();

    public MyTomcat() {
    }

    public MyTomcat(int port) {
        this.port = port;
    }

    public void start() throws IOException {
        //  初始化映射關係
        initServletMapping();

        // 啓動Selector
        selector = SelectorProvider.provider().openSelector();
        // 啓動Channel
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 配置非阻塞選擇
        ssc.configureBlocking(false);

        // 監聽端口
        InetSocketAddress isa = new InetSocketAddress(port);
        ssc.socket().bind(isa);

        // 將Channel綁定到Selector上,並選擇準備模式爲Accept,此處可能會失敗,後續可再次開啓
        SelectionKey acceptKey = ssc.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("MyTomcat is started...");

        ConcurrentLinkedQueue<MyRequest> requestList = new ConcurrentLinkedQueue<>();
        ConcurrentLinkedQueue<MyResponse> responseList = new ConcurrentLinkedQueue<>();

        while (true) {
            selector.select();  //  等待Channel準備數據
            Set readyKeys = selector.selectedKeys();
            Iterator i = readyKeys.iterator();

            while (i.hasNext()) {
                SelectionKey sk = (SelectionKey) i.next();
                i.remove(); //  從集合中移除,防止重複處理

                if (sk.isAcceptable()) { //  如果鍵的接收狀態未正常打開,再次嘗試打開
                    doAccept(sk);
                } else if (sk.isValid() && sk.isReadable()) {  // 可讀
                    requestList.add(getRequest(sk));
                    //  切換準備狀態
                    sk.interestOps(SelectionKey.OP_WRITE);
                } else if (sk.isValid() && sk.isWritable()) { //  可寫
                    responseList.add(getResponse(sk));
                    //  切換準備狀態
                    sk.interestOps(SelectionKey.OP_READ);
                }

                //  等待一對請求和響應均準備好時處理
                if (!requestList.isEmpty() && !responseList.isEmpty()) {
                    dispatch(requestList.poll(), responseList.poll());
                }
            }
        }
    }

    /**
     * 如果沒有正常開啓接收模式
     * 嘗試開啓接收模式
     * @param selectionKey
     */
    private void doAccept(SelectionKey selectionKey) {
        ServerSocketChannel server = (ServerSocketChannel) selectionKey.channel();
        SocketChannel clientChannel;
        try {
            clientChannel = server.accept();
            clientChannel.configureBlocking(false);

            SelectionKey clientKey = clientChannel.register(selector, SelectionKey.OP_READ);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 從通道中獲取請求並進行包裝
     *
     * @param selectionKey
     * @return
     * @throws IOException
     */
    private MyRequest getRequest(SelectionKey selectionKey) throws IOException {
        return new MyRequest(selectionKey);    //  包裝request
    }

    /**
     * 從通道中獲取響應並進行包裝
     *
     * @param selectionKey
     * @return
     */
    private MyResponse getResponse(SelectionKey selectionKey) {
        return new MyResponse(selectionKey);     //  包裝response
    }

    /**
     * 初始化Servlet的映射對象
     */
    private void initServletMapping() {
        for (ServletMapping servletMapping : ServletMappingConfig.servletMappingList) {
            urlServletMap.put(servletMapping.getUrl(), servletMapping.getClazz());
        }
    }

    /**
     * 請求調度
     *
     * @param myRequest
     * @param myResponse
     */
    private void dispatch(MyRequest myRequest, MyResponse myResponse) {
        if (myRequest == null) return;
        if (myResponse == null) return;
        String clazz = urlServletMap.get(myRequest.getUrl());

        try {
            if (clazz == null) {
                myResponse.write("404");
                return;
            }
            es.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Class<MyServlet> myServletClass = (Class<MyServlet>) Class.forName(clazz);
                        MyServlet myServlet = myServletClass.newInstance();
                        myServlet.service(myRequest, myResponse);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        new MyTomcat().start();
    }
}

測試

當我們在瀏覽器中輸入http://localhost:8080/world?data=yes時,成功得到了預期的結果

在這裏插入圖片描述

控制檯輸出:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章