设为首页 收藏本站
查看: 618|回复: 0

[经验分享] tomcat 源码分析之--请求接受以及缓冲池

[复制链接]

尚未签到

发表于 2017-2-6 11:37:08 | 显示全部楼层 |阅读模式
  tomcat  从接受请求到处理的流程大概如下:
  首先配置文件中的connector都对应一个Connector类,这个类根据配置信息确定对应的
  ProtocalHandler(处理connector配置对应的协议).

public void start() throws LifecycleException {
if( !initialized )
initialize();
// Validate and update our current state
if (started ) {
if(log.isInfoEnabled())
log.info(sm.getString("coyoteConnector.alreadyStarted"));
return;
}
lifecycle.fireLifecycleEvent(START_EVENT, null);
started = true;
// We can't register earlier - the JMX registration of this happens
// in Server.start callback
if ( this.oname != null ) {
// We are registred - register the adapter as well.
try {
Registry.getRegistry(null, null).registerComponent
(protocolHandler, createObjectName(this.domain,"ProtocolHandler"), null);
} catch (Exception ex) {
log.error(sm.getString
("coyoteConnector.protocolRegistrationFailed"), ex);
}
} else {
if(log.isInfoEnabled())
log.info(sm.getString
("coyoteConnector.cannotRegisterProtocol"));
}
try {
protocolHandler.start();
} catch (Exception e) {
String errPrefix = "";
if(this.service != null) {
errPrefix += "service.getName(): \"" + this.service.getName() + "\"; ";
}
throw new LifecycleException
(errPrefix + " " + sm.getString
("coyoteConnector.protocolHandlerStartFailed", e));
}
if( this.domain != null ) {
mapperListener.setDomain( domain );
//mapperListener.setEngine( service.getContainer().getName() );
mapperListener.init();
try {
ObjectName mapperOname = createObjectName(this.domain,"Mapper");
if (log.isDebugEnabled())
log.debug(sm.getString(
"coyoteConnector.MapperRegistration", mapperOname));
Registry.getRegistry(null, null).registerComponent
(mapper, mapperOname, "Mapper");
} catch (Exception ex) {
log.error(sm.getString
("coyoteConnector.protocolRegistrationFailed"), ex);
}
}
}
  抛开其他代码,注意上面方法里面的这一句:protocolHandler.start();
   比如http1.1协议对应的ProtocalHandler是:Http11Protocol。
  而这个ProtocalHanler依靠一个对应的EndPoint对象来处理请求,http11protocal的start方法代码
  如下:

public void start() throws Exception {
if (this.domain != null) {
try {
tpOname = new ObjectName
(domain + ":" + "type=ThreadPool,name=" + getName());
Registry.getRegistry(null, null)
.registerComponent(endpoint, tpOname, null );
} catch (Exception e) {
log.error("Can't register endpoint");
}
rgOname=new ObjectName
(domain + ":type=GlobalRequestProcessor,name=" + getName());
Registry.getRegistry(null, null).registerComponent
( cHandler.global, rgOname, null );
}
try {
endpoint.start();
} catch (Exception ex) {
log.error(sm.getString("http11protocol.endpoint.starterror"), ex);
throw ex;
}
if (log.isInfoEnabled())
log.info(sm.getString("http11protocol.start", getName()));
}
  注意其中的代码:        endpoint.start();
  Endpoint是对应的protocalhandler的工具类,每个endpoinst都监听一个对应的ServerSocket并且处理请求,start方法代码如下:

public void start()
throws Exception {
// Initialize socket if not done before
if (!initialized) {
init();
}
if (!running) {
running = true;
paused = false;
// Create worker collection
if (executor == null) {
workers = new WorkerStack(maxThreads);
}
// Start acceptor threads
for (int i = 0; i < acceptorThreadCount; i++) {
Thread acceptorThread = new Thread(new Acceptor(), getName() + "-Acceptor-" + i);
acceptorThread.setPriority(threadPriority);
acceptorThread.setDaemon(daemon);
acceptorThread.start();
}
}
}
  很容易看出,其实tomcat的请求监听也不是单线程的,有多个线程在进行监听。那么每个监听线程在监听到socket请求之后做什么工作呢?就是处理socket.这是通过调用Endpoint的processSocket方法实现的:

  protected boolean processSocket(Socket socket) {
try {
if (executor == null) {
getWorkerThread().assign(socket);
} else {
executor.execute(new SocketProcessor(socket));
}
} catch (Throwable t) {
// This means we got an OOM or similar creating a thread, or that
// the pool and its queue are full
log.error(sm.getString("endpoint.process.fail"), t);
return false;
}
return true;
}
  如果在  配置文件里面定义了一个executor,那么就使用此executor.否则使用默认的Worker缓冲池。下面就来分析一下worker缓冲池的实现:
  worker是存放在WorkerStack里面的,WorkerStack维护了一个worker数组。当endpoint里面需要worker线程的时候,会调用如下方法:

protected Worker createWorkerThread() {
synchronized (workers) {
if (workers.size() > 0) {
curThreadsBusy++;
return workers.pop();
}
if ((maxThreads > 0) && (curThreads < maxThreads)) {
curThreadsBusy++;
if (curThreadsBusy == maxThreads) {
log.info(sm.getString("endpoint.info.maxThreads",
Integer.toString(maxThreads), address,
Integer.toString(port)));
}
return (newWorkerThread());
} else {
if (maxThreads < 0) {
curThreadsBusy++;
return (newWorkerThread());
} else {
return (null);
}
}
}
}
  这个方法不多说了,一看就差不多明白大概原理。但是可能还有一点疑问:新增的worker如何放到WorkerStack里面呢? 这个就要看一下Worker的实现了:worker运行最后有一句代码:recycleWorkerThread。

    protected void recycleWorkerThread(Worker workerThread) {
synchronized (workers) {
workers.push(workerThread);
curThreadsBusy--;
workers.notify();
}
}
  至此,一个缓冲池轻松实现了。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-338306-1-1.html 上篇帖子: java配合tomcat实现动态2级域名效果 下篇帖子: Tomcat调整内存所能容纳的最大值
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表