springboot常用servlet容器是tomcat,底层NioEndpoint是基于nio实现的,但是该连接器从网络读写使用的是堆上创建的HeapBuffer,从网络写入写出都会发生二次拷贝,对性能影响较大。Netty是一款基于nio的网络编程框架,以零拷贝著称,如果能将tomcat底层endpoint用netty实现,既有完善的servlet功能,又增加了零拷贝,是不是可以有效提高tomcat性能呢。但是两者的数据处理思想不同。如果将两者结合需要解决几个难点:
一、tomcat是在socket有数据以后将socket包装一下提交到后续处理,后续如果需要继续读数据,可以直接读取,tomcat后续所有代码都是在这个前提下写的。而netty在拿到网络传过来的数据以后直接把数据提交给后续处理,并没有暴露底层socket,无法继续读取数据,只能等待下次读数据就绪事件触发。因此我将tomcat的socket和netty的数据重新包装成自定义的channel,提取公共的部分定义成接口。
public interface Channel<E> {
public BufWrapper getAppReadBuffer();
public void initAppReadBuffer(int headerBufferSize);
public boolean fillAppReadBuffer(boolean block) throws IOException;
public BufWrapper allocate(int size);
public E getSocket();
public Object getCurrentProcessor();
public void setCurrentProcessor(Object currentProcessor);
// public void execute(Runnable runnable);
public IOException getError();
public void setUpgraded(boolean upgraded);
public String getNegotiatedProtocol();
public void setNegotiatedProtocol(String negotiatedProtocol);
public void setReadTimeout(long readTimeout);
public long getReadTimeout();
public void setWriteTimeout(long writeTimeout