介绍
作为常用的http
协议服务器,tomcat
应用非常广泛。tomcat也是遵循servelt协议的,servelt
协议可以让服务器与真实服务逻辑代码进行解耦。各自只需要关注servlet
协议即可。
对于tomcat是如何作为一个高性能的服务器的呢?你是不是也会有这样的疑问?
tomcat是如何接收网络请求?
如何做到高性能的http
协议服务器?
tomcat从8.0往后开始使用了nio非阻塞io模型,提高了吞吐量,本文的源码是tomcat 9.0.48版本
接收socket请求
org.apache.tomcat.util.net.acceptor
实现了runnable
接口,在一个单独的线程中以死循环的方式一直进行socket的监听
线程的初始化及启动是在方法org.apache.tomcat.util.net.abstractendpoint#startacceptorthread
有个很重要的属性org.apache.tomcat.util.net.abstractendpoint
;同时实现了run
方法,方法中主要有以下功能:
- 请求最大连接数限制: 最大为 8*1024;请你注意到达最大连接数后操作系统底层还是会接收客户端连接,但用户层已经不再接收
- 获取
socketchannel
public void run() { int errordelay = 0; try { // loop until we receive a shutdown command while (!stopcalled) { ... if (stopcalled) { break; } state = acceptorstate.running; try { //if we have reached max connections, wait // 如果连接超过了 8*1024,则线程阻塞等待; 是使用org.apache.tomcat.util.threads.limitlatch类实现了分享锁(内部实现了abstractqueuedsynchronizer) // 请你注意到达最大连接数后操作系统底层还是会接收客户端连接,但用户层已经不再接收。 endpoint.countuporawaitconnection(); // endpoint might have been paused while waiting for latch // if that is the case, don't accept new connections if (endpoint.ispaused()) { continue; } u socket = null; try { // accept the next incoming connection from the server // socket // 抽象方法,不同的endpoint有不同的实现方法。nioendpoint为例,实现方法为serversock.accept(),这个方法主要看serversock实例化时如果为阻塞,accept方法为阻塞;反之为立即返回,如果没有socket链接,则为null socket = endpoint.serversocketaccept(); } catch (exception ioe) { // we didn't get a socket endpoint.countdownconnection(); if (endpoint.isrunning()) { // introduce delay if necessary errordelay = handleexceptionwithdelay(errordelay); // re-throw throw ioe; } else { break; } } // successful accept, reset the error delay errordelay = 0; // configure the socket if (!stopcalled && !endpoint.ispaused()) { // setsocketoptions() will hand the socket off to // an appropriate processor if successful // endpoint类的抽象方法,不同的endpoint有不同的实现。处理获取到的socketchannel链接,如果该socket链接能正常处理,那么该方法会返回true,否则为false if (!endpoint.setsocketoptions(socket)) { endpoint.closesocket(socket); } } else { endpoint.destroysocket(socket); } } catch (throwable t) { ... } } } finally { stoplatch.countdown(); } state = acceptorstate.ended; }
再来看下org.apache.tomcat.util.net.nioendpoint#setsocketoptions
方法的具体实现(nioendpoint为例)
这个方法中主要做的事:
- 创建niochannel
- 设置socket为非阻塞
- 将socket添加到poller的队列中
protected boolean setsocketoptions(socketchannel socket) { niosocketwrapper socketwrapper = null; try { // allocate channel and wrapper // 优先使用已有的缓存niochannel niochannel channel = null; if (niochannels != null) { channel = niochannels.pop(); } if (channel == null) { socketbufferhandler bufhandler = new socketbufferhandler( socketproperties.getappreadbufsize(), socketproperties.getappwritebufsize(), socketproperties.getdirectbuffer()); if (issslenabled()) { channel = new secureniochannel(bufhandler, this); } else { channel = new niochannel(bufhandler); } } // 将nioendpoint与niochannel进行包装 niosocketwrapper newwrapper = new niosocketwrapper(channel, this); channel.reset(socket, newwrapper); connections.put(socket, newwrapper); socketwrapper = newwrapper; // set socket properties // disable blocking, polling will be used // 设置当前链接的socket为非阻塞 socket.configureblocking(false); if (getunixdomainsocketpath() == null) { socketproperties.setproperties(socket.socket()); } socketwrapper.setreadtimeout(getconnectiontimeout()); socketwrapper.setwritetimeout(getconnectiontimeout()); socketwrapper.setkeepaliveleft(nioendpoint.this.getmaxkeepaliverequests()); // 将包装后的niochannel与nioendpoint进行注册,注册到poller,将对应的socket包装类添加到poller的队列中,同时唤醒selector poller.register(socketwrapper); return true; } catch (throwable t) { exceptionutils.handlethrowable(t); try { log.error(sm.getstring("endpoint.socketoptionserror"), t); } catch (throwable tt) { exceptionutils.handlethrowable(tt); } if (socketwrapper == null) { destroysocket(socket); } } // tell to close the socket if needed return false; }
socket请求轮询
上一小节是接收到了socket请求,进行包装之后,将socket添加到了poller
的队列上,并可能唤醒了selector
,本小节就来看看,poller是如何进行socket的轮询的。
首先org.apache.tomcat.util.net.nioendpoint.poller
也是实现了runnable接口,是一个可以单独启动的线程
初始化及启动是在org.apache.tomcat.util.net.nioendpoint#startinternal
重要的属性:
java.nio.channels.selector
:在poller对象初始化的时候,就会启动轮询器synchronizedqueue<pollerevent>
:同步的事件队列
再来看下具体处理逻辑,run方法的源码
public void run() { // loop until destroy() is called while (true) { boolean hasevents = false; try { if (!close) { // 去synchronizedqueue事件队列中拉去,看是否已经有了事件,如果有,则返回true // 如果从队列中拉取到了event(即上一步将niosocketwrapper封装为pollerevent添加到次队列中),将socketchannel注册到selector上,标记为selectionkey.op_read,添加处理函数attachment(为accetpor添加到poller时的 // niosocketwrapper) hasevents = events(); if (wakeupcounter.getandset(-1) > 0) { // if we are here, means we have other stuff to do // do a non blocking select keycount = selector.selectnow(); } else { keycount = selector.select(selectortimeout); } wakeupcounter.set(0); } if (close) { events(); timeout(0, false); try { selector.close(); } catch (ioexception ioe) { log.error(sm.getstring("endpoint.nio.selectorclosefail"), ioe); } break; } // either we timed out or we woke up, process events first if (keycount == 0) { hasevents = (hasevents | events()); } } catch (throwable x) { exceptionutils.handlethrowable(x); log.error(sm.getstring("endpoint.nio.selectorlooperror"), x); continue; } iterator<selectionkey> iterator = keycount > 0 ? selector.selectedkeys().iterator() : null; // walk through the collection of ready keys and dispatch // any active event. // selector轮询获取已经注册的事件,如果有事件准备好,此时通过selectkeys方法就能拿到对应的事件 while (iterator != null && iterator.hasnext()) { selectionkey sk = iterator.next(); // 获取到事件后,从迭代器删除事件,防止事件重复轮询 iterator.remove(); // 获取事件的处理器,这个attachment是在event()方法中注册的,后续这个事件的处理,就交给这个wrapper去处理 niosocketwrapper socketwrapper = (niosocketwrapper) sk.attachment(); // attachment may be null if another thread has called // cancelledkey() if (socketwrapper != null) { processkey(sk, socketwrapper); } } // process timeouts timeout(keycount,hasevents); } getstoplatch().countdown(); }
在这里,有一个很重要的方法,org.apache.tomcat.util.net.nioendpoint.poller#events()
,他是从poller
的事件队列中获取acceptor
接收到的可用socket,并将其注册到selector
上
/** * processes events in the event queue of the poller. * * @return <code>true</code> if some events were processed, * <code>false</code> if queue was empty */ public boolean events() { boolean result = false; pollerevent pe = null; // 如果acceptor将socket添加到队列中,那么events.poll()方法就能拿到对应的事件,否则拿不到就返回false for (int i = 0, size = events.size(); i < size && (pe = events.poll()) != null; i++ ) { result = true; niosocketwrapper socketwrapper = pe.getsocketwrapper(); socketchannel sc = socketwrapper.getsocket().getiochannel(); int interestops = pe.getinterestops(); if (sc == null) { log.warn(sm.getstring("endpoint.nio.nullsocketchannel")); socketwrapper.close(); } else if (interestops == op_register) { // 如果是acceptor刚添加到队列中的事件,那么此时的ops就是op_register try {, // 将次socket注册到selector上,标记为op_read事件,添加事件触发时处理函数socketwrapper sc.register(getselector(), selectionkey.op_read, socketwrapper); } catch (exception x) { log.error(sm.getstring("endpoint.nio.registerfail"), x); } } else { // ??这里的逻辑,不清楚什么情况下会进入到这个分支里面 final selectionkey key = sc.keyfor(getselector()); if (key == null) { // the key was cancelled (e.g. due to socket closure) // and removed from the selector while it was being // processed. count down the connections at this point // since it won't have been counted down when the socket // closed. socketwrapper.close(); } else { final niosocketwrapper attachment = (niosocketwrapper) key.attachment(); if (attachment != null) { // we are registering the key to start with, reset the fairness counter. try { int ops = key.interestops() | interestops; attachment.interestops(ops); key.interestops(ops); } catch (cancelledkeyexception ckx) { cancelledkey(key, socketwrapper); } } else { cancelledkey(key, socketwrapper); } } } if (running && !paused && eventcache != null) { pe.reset(); eventcache.push(pe); } } return result; }
还有一个重要方法就是org.apache.tomcat.util.net.nioendpoint.poller#processkey
,上一个方法是获取event,并注册到selector,那这个方法就是通过selector
获取到的数据准备好的event,并开始封装成对应的业务处理线程socketprocessorbase
,扔到线程池里开始处理
protected void processkey(selectionkey sk, niosocketwrapper socketwrapper) { try { if (close) { cancelledkey(sk, socketwrapper); } else if (sk.isvalid()) { if (sk.isreadable() || sk.iswritable()) { if (socketwrapper.getsendfiledata() != null) { processsendfile(sk, socketwrapper, false); } else { unreg(sk, socketwrapper, sk.readyops()); boolean closesocket = false; // read goes before write if (sk.isreadable()) { //这里如果是异步的操作,就会走这里 if (socketwrapper.readoperation != null) { if (!socketwrapper.readoperation.process()) { closesocket = true; } } else if (socketwrapper.readblocking) { // readblocking默认为false synchronized (socketwrapper.readlock) { socketwrapper.readblocking = false; socketwrapper.readlock.notify(); } } else if (!processsocket(socketwrapper, socketevent.open_read, true)) { // 处理正常的事件,这里的processsocket就要正式开始处理请求了。 // 将对应的事件封装成对应的线程,然后交给线程池去处理正式的请求业务 closesocket = true; } } if (!closesocket && sk.iswritable()) { if (socketwrapper.writeoperation != null) { if (!socketwrapper.writeoperation.process()) { closesocket = true; } } else if (socketwrapper.writeblocking) { synchronized (socketwrapper.writelock) { socketwrapper.writeblocking = false; socketwrapper.writelock.notify(); } } else if (!processsocket(socketwrapper, socketevent.open_write, true)) { closesocket = true; } } if (closesocket) { cancelledkey(sk, socketwrapper); } } } } else { // invalid key cancelledkey(sk, socketwrapper); } } catch (cancelledkeyexception ckx) { cancelledkey(sk, socketwrapper); } catch (throwable t) { exceptionutils.handlethrowable(t); log.error(sm.getstring("endpoint.nio.keyprocessingerror"), t); } }
请求具体处理
上一步,selector获取到了就绪的请求socket,然后根据socket注册的触发处理函数等,将这些数据进行封装,扔到了线程池里,开始具体的业务逻辑处理。本节就是从工作线程封装开始,org.apache.tomcat.util.net.socketprocessorbase
为工作线程类的抽象类,实现了runnable接口,不同的endpoint实现具体的处理逻辑,本节以nioendpoint为例
以下为org.apache.tomcat.util.net.abstractendpoint#processsocket
方法源码
/** * process the given socketwrapper with the given status. used to trigger * processing as if the poller (for those endpoints that have one) * selected the socket. * * @param socketwrapper the socket wrapper to process * @param event the socket event to be processed * @param dispatch should the processing be performed on a new * container thread * * @return if processing was triggered successfully */ public boolean processsocket(socketwrapperbase<s> socketwrapper, socketevent event, boolean dispatch) { try { if (socketwrapper == null) { return false; } // 优先使用已经存在的线程 socketprocessorbase<s> sc = null; if (processorcache != null) { sc = processorcache.pop(); } if (sc == null) { sc = createsocketprocessor(socketwrapper, event); } else { sc.reset(socketwrapper, event); } // 获取线程池。线程池的初始化,是在acceptor、poller这两个单独线程启动之前创建 // tomcat使用了自定义的org.apache.tomcat.util.threads.taskqueue,这块tomcat也进行了小的适配开发 // 核心线程为10个,最大200线程 executor executor = getexecutor(); if (dispatch && executor != null) { executor.execute(sc); } else { sc.run(); } } catch (rejectedexecutionexception ree) { getlog().warn(sm.getstring("endpoint.executor.fail", socketwrapper) , ree); return false; } catch (throwable t) { exceptionutils.handlethrowable(t); // this means we got an oom or similar creating a thread, or that // the pool and its queue are full getlog().error(sm.getstring("endpoint.process.fail"), t); return false; } return true; }
上面的方法是得到了处理业务逻辑的线程socketprocessorbase,nioendpoint内部类org.apache.tomcat.util.net.nioendpoint.socketprocessor
继承了这个抽象类,也就是具体的业务处理逻辑在org.apache.tomcat.util.net.nioendpoint.socketprocessor#dorun
方法中,最终调用到我们的servlet
protected void dorun() { /* * do not cache and re-use the value of socketwrapper.getsocket() in * this method. if the socket closes the value will be updated to * closed_nio_channel and the previous value potentially re-used for * a new connection. that can result in a stale cached value which * in turn can result in unintentionally closing currently active * connections. */ poller poller = nioendpoint.this.poller; if (poller == null) { socketwrapper.close(); return; } try { int handshake = -1; try { // 握手相关判断逻辑 ... } catch (ioexception x) { ... } // 三次握手成功了 if (handshake == 0) { socketstate state = socketstate.open; // process the request from this socket // event为socketevent.open_read,这个变量是org.apache.tomcat.util.net.nioendpoint.poller#processkey方法赋值 if (event == null) { state = gethandler().process(socketwrapper, socketevent.open_read); } else { // 这里就开始正式处理请求了 state = gethandler().process(socketwrapper, event); } if (state == socketstate.closed) { poller.cancelledkey(getselectionkey(), socketwrapper); } } else if (handshake == -1 ) { gethandler().process(socketwrapper, socketevent.connect_fail); poller.cancelledkey(getselectionkey(), socketwrapper); } else if (handshake == selectionkey.op_read){ socketwrapper.registerreadinterest(); } else if (handshake == selectionkey.op_write){ socketwrapper.registerwriteinterest(); } } catch (cancelledkeyexception cx) { poller.cancelledkey(getselectionkey(), socketwrapper); } catch (virtualmachineerror vme) { exceptionutils.handlethrowable(vme); } catch (throwable t) { log.error(sm.getstring("endpoint.processing.fail"), t); poller.cancelledkey(getselectionkey(), socketwrapper); } finally { socketwrapper = null; event = null; //return to cache if (running && !paused && processorcache != null) { processorcache.push(this); } } }
总结
-
tomcat
是如何接收网络请求?使用java nio的同步非阻塞去进行网络监听。
org.apache.tomcat.util.net.abstractendpoint#bindwithcleanup
中初始化网络监听、ssl{ .... serversock = serversocketchannel.open(); socketproperties.setproperties(serversock.socket()); inetsocketaddress addr = new inetsocketaddress(getaddress(), getportwithoffset()); // 当应用层面的连接数到达最大值时,操作系统可以继续接收连接,那么操作系统能继续接收的最大连接数就是这个队列长度,可以通过acceptcount 参数配置,默认是 100 serversock.bind(addr, getacceptcount()); } serversock.configureblocking(true); //mimic apr behavior
org.apache.tomcat.util.net.nioendpoint#startinternal
中初始化业务处理的线程池、连接限制器、poller线程、acceptor线程 -
如何做到高性能的
http
协议服务器?tomcat把接收连接、检测 i/o 事件以及处理请求进行了拆分,用不同规模的线程去做对应的事情,这也是tomcat能高并发处理请求的原因。不让线程阻塞,尽量让cpu忙起来
-
是怎么设计的呢?
通过接口、抽象类等,将不同的处理逻辑拆分,各司其职
org.apache.tomcat.util.net.abstractendpoint
:i/o事件的检测、处理逻辑都在这个类的实现类里面。使用模板方法,不同的协议有不同的实现方法。nioendpoint/nio2endpoint/aprendpointorg.apache.tomcat.util.net.nioendpoint.poller
:引用了java.nio.channels.selector
,内部有个事件队列,监听i/o事件具体就是在这里做的org.apache.tomcat.util.net.nioendpoint.niosocketwrapper
org.apache.tomcat.util.net.nioendpoint.socketprocessor
: 具体处理请求的线程类
参考:
nioendpoint组件:tomcat如何实现非阻塞i/o?
java nio浅析
到此这篇关于apache tomcat如何高并发处理请求 的文章就介绍到这了,更多相关apache tomcat高并发请求 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!