自上次使用Openresty+Lua+Nginx的来加速本身的网站,用上了比较时髦的技术,感受算是让本身的网站响应速度达到极限了,直到看到了Netty,公司就是打算用Netty来替代Openresty这一套,因此,本身也学了很久,琢磨了好一趟才知道怎么用,如今用来写一套HTTP代理服务器吧,以后再测试一下性能。html
以前相关的文章以下:
【网页加速】lua redis的二次升级
使用Openresty加快网页速度java
参考自《Netty实战》git
FullHttpRequest:
github
FullHttpResponse:
redis
在实现Http代理服务器以前,咱们先来查看一下Netty实现代理服务器的完整流程:
centos
Netty的Http服务的流程是:
一、Client向Server发送http请求,在一般的状况中,client通常指的是浏览器,也能够由本身用netty实现一个客户端。此时,客户端须要用到HttpRequestEncoder将http请求进行编码。
二、Server端对http请求进行解析,服务端中,须要用到HttpRequestDecoder来对请求进行解码,而后实现本身的业务需求。
三、Server端向client发送http响应,处理完业务需求后,将相应的内容,用HttpResponseEncoder进行编码,返回数据。
四、Client对http响应进行解析,用HttpResponseDecoder进行解码。浏览器
而Netty实现Http代理服务器的过程跟上面的所说无心,只不过是在本身的业务层增长了回源到tomcat服务器这一过程。结合上本身以前实现过的用OpenResty+Nginx来作代理服务器这一套,此处的Netty实现的过程也与此相似。此处粘贴一下OpenResty+Nginx实现的流程图:
tomcat
而使用了Netty以后,即是将中间的OpenResty+Nginx换成了Netty,下面咱们来看一下具体的实现过程。服务器
public class HttpServer { public void start(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .handler(new LoggingHandler(LogLevel.DEBUG)) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { // server端发送的是httpResponse,因此要使用HttpResponseEncoder进行编码 ch.pipeline().addLast( new HttpResponseEncoder()); // server端接收到的是httpRequest,因此要使用HttpRequestDecoder进行解码 ch.pipeline().addLast( new HttpRequestDecoder()); ch.pipeline().addLast( new HttpServerHandler()); //增长自定义实现的Handler ch.pipeline().addLast(new HttpServerCodec()); } }).option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { HttpServer server = new HttpServer(); server.start(8080); } }
@Slf4j public class HttpServerHandler extends ChannelInboundHandlerAdapter { private RedisUtil redisUtil = new RedisUtil(); @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { DefaultHttpRequest request = (DefaultHttpRequest) msg; String uri = request.uri(); if ("/favicon.ico".equals(uri)) { return; } log.info(new Date().toString()); Jedis jedis = redisUtil.getJedis(); String s = jedis.get(uri); if (s == null || s.length() == 0) { //这里咱们的处理是回源到tomcat服务器进行抓取,而后 //将抓取的内容放回到redis里面 try { URL url = new URL("http://119.29.188.224:8080" + uri); log.info(url.toString()); URLConnection urlConnection = url.openConnection(); HttpURLConnection connection = (HttpURLConnection) urlConnection; connection.setRequestMethod("GET"); //链接 connection.connect(); //获得响应码 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader (connection.getInputStream(), StandardCharsets.UTF_8)); StringBuilder bs = new StringBuilder(); String l; while ((l = bufferedReader.readLine()) != null) { bs.append(l).append("\n"); } s = bs.toString(); } jedis.set(uri, s); connection.disconnect(); } catch (Exception e) { log.error("", e); return; } } jedis.close(); FullHttpResponse response = new DefaultFullHttpResponse( HTTP_1_1, OK, Unpooled.wrappedBuffer(s != null ? s .getBytes() : new byte[0])); response.headers().set(CONTENT_TYPE, "text/html"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(response); ctx.flush(); } else { //这里必须加抛出异常,要否则ab测试的时候一直卡住不动,暂未解决 throw new Exception(); } } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } }
下面的是ab测试,在1GHz、2G内存的centos7机器(阿里云服务器)下进行测试,测试命令ab -c 100 -n 10000 localhost:8000/,并发数为100,总数为10000。并发
性能:
总体响应时间的分布比(单位:ms):
看完以后,我本身也震惊了,Netty实现的不只稳定、吞吐率还比OpenResty的高出一倍,OpenResty的竟然还有那么多的失败次数,不知是否是个人代码的问题仍是测试例子不规范,至今,我仍是OpenResty的脑残粉。整体的来讲,Netty实现的服务器性能仍是比较强的,不只可以快速地开发高性能的面向协议的服务器和客户端,还能够在Netty上轻松实现各类自定义的协议。
https://github.com/Zephery/myway
参考: