前面的文章(http://xylong.iteye.com/blog/1841579)简要讲述了douyu的大致结构,这里我将带大家开启douyu请求的征程,其实web服务器简要的讲无非请求响应的一个过程,脱离不了http/tcp-ip等网络协议,如何接受请求,处理请求,直至应用web容器(更准确地说是java这块是servlet)的API,对接具体的业务逻辑,不论是很早的技术(jsp-servlet),还是近些年的struts等都是如此,上面只是自己一个比较粗糙的认识,只想给各位看官一个大致的认识,更细节性的东西,下面慢慢讲。
douyu-startup中的Server作为服务器的启动类
Server server = new Server(); // Connector ajp = new AjpConnector(); Connector http = new HttpConnector(); // server.addConnectors(ajp, http); // server.addConnector(ajp); server.addConnector(http); String baseDir = new File(".").getCanonicalPath(); String srcDir = new File(baseDir, "src/main/java").getCanonicalPath(); System.out.println("src dir: " + srcDir); String resourcesDir = new File(baseDir, "src/main/resources").getCanonicalPath(); server.getConfig().addClassPath(resourcesDir); System.out.println("resources dir: " + resourcesDir); String classesDir = new File(baseDir, "douyu-examples-classes").getCanonicalPath(); System.out.println("classes dir: " + classesDir); //初始化参数,应用名称,编码格式等 server.init("douyu-examples", "UTF-8", srcDir, classesDir, true, null); //启动方式 server.start();
上面的示例很明显地提供了两种协议处理方式(http/ajp),如果不指定处理方式,默认是httpConnector,httpConnector与AjpConnector有一个共同的抽象父类Connector,在Connector的start()方法中,我们很惊奇地看到了douyu是如何集成netty框架的,
this.config = config;
// Configure the server.
ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors
.newCachedThreadPool(), Executors.newCachedThreadPool()));
// Set up the event pipeline factory.
bootstrap.setPipelineFactory(getChannelPipelineFactory());
// Bind and start to accept incoming connections.
bootstrap.bind(new InetSocketAddress(host, port));
上面代码标红的地方其实是一个抽象方法,留给httpConnector与ajpConnector的不同协议的处理方式,一个比较实用的设计模式,下面我们看看httpConnector的处理过程。