为了账号安全,请及时绑定邮箱和手机立即绑定

四种方法实现http服务

标签:
Java

前言:对于微服务来说,如果我们要实现一个web服务,
大部分人可能直接用springboot的spring-boot-starter-web了。
我们知道spring-boot-starter-web默认实现是tomcat,当然你也可以选择其他服务器类型,比如Jetty、Undertow等。
但是如果是一个非springboot项目,该如何实现呢?

这里介绍了下四种实现方式,基于Tomcat、Jetty、JdkHttp、Netty实现内嵌web容器。

Tomcat

依赖的maven坐标:

        javax.annotationjavax.annotation-apiorg.apache.tomcat.embedtomcat-embed-coretomcat-annotations-apiorg.apache.tomcat

首先看下初始化启动的代码:

Tomcat tomcatServer = new Tomcat();
//静默方式启动
tomcatServer.setSilent(true);

tomcatServer.setPort(8080);
//是否设置自动部署
tomcatServer.getHost().setAutoDeploy(false);
//创建上下文,拿到上下文后就可以设置整个访问地址了
StandardContext standardContext = new StandardContext();
standardContext.setPath(CONTEX_PATH);
//监听上下文
standardContext.addLifecycleListener(new Tomcat.FixContextListener());
// tomcat容器添加standardContext 添加整个context
tomcatServer.getHost().addChild(standardContext);
// 创建servlet   servlet的名字叫IndexServlet
tomcatServer.addServlet(CONTEX_PATH, SERVLET_NAME, new JdkSimpleDispatchServlet());
// 添加servleturl映射
standardContext.addServletMappingDecoded("/*", SERVLET_NAME);
try {
    tomcatServer.start();
    server = tomcatServer;

} catch (Exception e) {
}

上面tomcat在注册servlet的时候,自定义了一个Servlet,然后映射了/*的请求。可以查看下JdkSimpleDispatchServlet这个类,代码如下:

@Slf4j
public class JdkSimpleDispatchServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.info("path:{}, clientIp:{}", req.getRequestURL(), req.getRemoteHost());
        PrintWriter writer = resp.getWriter();
        writer.print("this is index");
        writer.close();

    }
}

Jetty

Jetty和tomcat非常类似,也是调用start方法启动。

maven依赖如下:

        org.eclipse.jettyjetty-serverorg.eclipse.jettyjetty-servlet

jetty服务初始化代码更简单,如下:

Server server = new Server(NetworkUtil.getHealthServerPort());

// ServletHandler是一种简单的创建上下文处理程序的简单方法,该上下文处理程序由Servlet实例支持。然后,需要将该处理程序注册到Server对象。
ServletHandler handler = new ServletHandler();
server.setHandler(handler);

// 这是原始Servlet,而不是已配置的Servlet,JdkSimpleDispatchServlet和tomcat的类似
handler.addServletWithMapping(JdkSimpleDispatchServlet.class, "/*");
try {
    // Start things up!
    server.start();
    jetty = server;

} catch (Exception e) {
}

Netty

说了Tomcat和Jetty,我们再看下Netty,之前所在的一家公司就是基于Netty封装了Web服务,Netty对Web支持也比较完善,默认基于NIO的多路复用IO模型支持单机上万的吞肚量。

看下pom依赖:

       io.nettynetty-all

启动方式:

public class NettyHttpServerHealthCheckServer implements IHealthCheckServer {
    private static ExecutorService Pool = Executors.newSingleThreadExecutor(
            new NamedThreadFactory("Netty-HealthCheck-Pool", true));
    ServerBootstrap bootstrap = new ServerBootstrap();
    // boss线程,只需一个
    EventLoopGroup boss = new NioEventLoopGroup();
    // work线程
    EventLoopGroup work = new NioEventLoopGroup();

    @Override
    public void start() {
        try {
            // 因为监听服务是阻塞的,需要线程池异步监听
            Pool.execute(() -> {
                try {
                    // 配置channel、handle
                    bootstrap.group(boss, work)
//                            .handler(new LoggingHandler(LogLevel.INFO))
                            .channel(NioServerSocketChannel.class)
                            // HttpServerInitializer即http编码解码和处理配置器
                            .childHandler(new HttpServerInitializer());
                    ChannelFuture f = bootstrap.bind(new InetSocketAddress(NetworkUtil.getHealthServerPort())).sync();
                    // 阻塞监听
                    f.channel().closeFuture().sync();

                } catch (Exception e) {
                }
            });
        } catch (Exception e) {
            return;
        }
    }


    @Override
    public void stop() {
        boss.shutdownGracefully();
        work.shutdownGracefully();
    }

    class HttpServerInitializer extends ChannelInitializer {

        @Override
        protected void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast(new HttpServerCodec());// http 编解码
            pipeline.addLast("httpAggregator", new HttpObjectAggregator(512 * 1024)); // http 消息聚合器                                                                     512*1024为接收的最大contentlength
            pipeline.addLast(new HttpRequestHandler());// 请求处理器
        }
    }

    class HttpRequestHandler extends SimpleChannelInboundHandler {

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) {
            ctx.flush();
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
            /**
             * 100 Continue
             * 是这样的一种情况:HTTP客户端程序有一个实体的主体部分要发送给服务器,但希望在发送之前查看下服务器是否会
             * 接受这个实体,所以在发送实体之前先发送了一个携带100
             * Continue的Expect请求首部的请求。服务器在收到这样的请求后,应该用 100 Continue或一条错误码来进行响应。
             */
            if (is100ContinueExpected(req)) {
                ctx.write(new DefaultFullHttpResponse(
                        HttpVersion.HTTP_1_1,
                        HttpResponseStatus.CONTINUE));
            }
            // 获取请求的uri
            String path = req.uri();
    
            // 响应请求
            fireResponse(ctx, HttpResponseStatus.OK,
                    "hello", "text/html; charset=utf-8");

        }

        private void fireResponse(ChannelHandlerContext ctx, HttpResponseStatus httpResponseStatus, String resp, String contentType) {
            FullHttpResponse responseDown = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1,
                    httpResponseStatus,
                    Unpooled.copiedBuffer(resp, Charset.defaultCharset()));
            responseDown.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType);
            ctx.writeAndFlush(responseDown).addListener(ChannelFutureListener.CLOSE);
        }
    }

}

从上面代码可以得知,Netty默认就提供了http编解码和协议的实现,非常方便。

JdkHttp

最好介绍下不依赖第三方实现,使用JDK8内置的Http Server实现。

HttpServer类

核心类HttpServer,HttpServer是属于rt包的类,需要下载rt包的源码,配置到IDEA。或者直接使用openjdk,也可以查看到源码。

rt包可以下载OpenJDK的源码,download.java.net/openjdk/jdk8/promoted/b132/openjdk-8-src-b132-03_mar_2014.zip

HttpServer源码:

package com.sun.net.httpserver;
@Exported
public abstract class HttpServer {
    protected HttpServer() {
    }
    public static HttpServer create() throws IOException {
        return create((InetSocketAddress)null, 0);
    }
    public static HttpServer create(InetSocketAddress var0, int var1) throws IOException {
        HttpServerProvider var2 = HttpServerProvider.provider();
        return var2.createHttpServer(var0, var1);
    }
    public abstract void bind(InetSocketAddress var1, int var2) throws IOException;
    public abstract void start();
    public abstract void setExecutor(Executor var1);
    public abstract Executor getExecutor();
    public abstract void stop(int var1);
    public abstract HttpContext createContext(String var1, HttpHandler var2);
    public abstract HttpContext createContext(String var1);
    public abstract void removeContext(String var1) throws IllegalArgumentException;
    public abstract void removeContext(HttpContext var1);
    public abstract InetSocketAddress getAddress();
}

初始化Http服务:

public class JDKHttpServerHealthCheckServer implements IHealthCheckServer {
    HttpServer server;

    @Override
    public void start() {
        try {
            // 初始化监听
            server = HttpServer.create(new InetSocketAddress(8080), 100);
            // 注册http请求处理类
            server.createContext("/", new JdkHttpHandler());
            // 启动服务
            server.start();
        } catch (Exception e) {
            return;
        }
    }

    @Override
    public void stop() {
        if (server != null) {
            server.stop(0);
        }
    }

    static class JdkHttpHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange httpExchange) throws IOException {
            String path = httpExchange.getRequestURI() == null ? "/" : httpExchange.getRequestURI().getPath();

            try {
                CharArrayWriter charArrayWriter = new CharArrayWriter();
                charArrayWriter.write("hello");
                httpExchange.getResponseHeaders().add("Content-Type", "text/plain; charset=utf-8");
                // 这里必须指定字节大小,因为默认是固定大小的编码解码实现
                httpExchange.sendResponseHeaders(200, charArrayWriter.size());
                outputStream.write(charArrayWriter.toString().getBytes());
                 
            } catch (Exception e) {
                httpExchange.sendResponseHeaders(500, 0);
            }
        }
    }
}

从上面四个实现来看,对http servlet规范支持比较完善的有Jetty、Tomcat。性能高的是Netty,实现最简单的是JDK默认HttpServer。

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消