Java 使用Netty构建http代理服务器的简单方法?

Java 使用Netty构建http代理服务器的简单方法?,java,netty,Java,Netty,我是Netty的新手,正在考虑使用它来创建一个简单的http代理服务器,该服务器接收来自客户端的请求,将请求转发到另一台服务器,然后将响应复制回原始请求的响应。一个额外的要求是,我能够支持超时,这样,如果代理服务器的响应时间过长,代理服务器将自行响应并关闭与代理服务器的连接 我已经使用Jetty实现了这样一个应用程序,但是使用Jetty我需要使用太多的线程来阻止入站请求(这是一个轻量级应用程序,使用很少的内存或cpu,但代理服务器的延迟足够高,流量突发会导致在代理服务器中排队,或者需要太多线程)

我是Netty的新手,正在考虑使用它来创建一个简单的http代理服务器,该服务器接收来自客户端的请求,将请求转发到另一台服务器,然后将响应复制回原始请求的响应。一个额外的要求是,我能够支持超时,这样,如果代理服务器的响应时间过长,代理服务器将自行响应并关闭与代理服务器的连接

我已经使用Jetty实现了这样一个应用程序,但是使用Jetty我需要使用太多的线程来阻止入站请求(这是一个轻量级应用程序,使用很少的内存或cpu,但代理服务器的延迟足够高,流量突发会导致在代理服务器中排队,或者需要太多线程)

根据我的理解,我可以使用Netty构建一个管道,其中每个阶段执行少量计算,然后释放其线程并等待数据准备就绪,以便管道中的下一个阶段执行

我的问题是,有这样一个应用程序的简单示例吗?到目前为止,我只对基本Netty教程的服务器代码进行了简单的修改,但它缺乏对客户端的所有支持。我看过Netty客户端教程,但不确定如何混合使用这两个教程中的代码来创建一个简单的代理应用程序

public static void main(String[] args) throws Exception {
    ChannelFactory factory =
            new NioServerSocketChannelFactory(
                    Executors.newCachedThreadPool(),
                    Executors.newCachedThreadPool());

    ServerBootstrap bootstrap = new ServerBootstrap(factory);

    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            return Channels.pipeline(
                    new HttpRequestDecoder(),
                    new HttpResponseEncoder(),
                    /* 
                     * Is there something I can put here to make a
                     * request to another server asynchronously and
                     * copy the result to the response inside
                     * MySimpleChannelHandler?
                     */
                    new MySimpleChannelHandler()
                    );
        }
    });

    bootstrap.setOption("child.tcpNoDelay", true);
    bootstrap.setOption("child.keepAlive", true);

    bootstrap.bind(new InetSocketAddress(8080));
}

private static class MySimpleChannelHandler extends SimpleChannelHandler {

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        HttpRequest request = (HttpRequest) e.getMessage();
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        response.setContent(request.getContent());

        Channel ch = e.getChannel();
        ChannelFuture f = ch.write(response);
        f.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) {
                Channel ch = future.getChannel();
                ch.close();
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        e.getCause().printStackTrace();

        Channel ch = e.getChannel();
        ch.close();
    }
}

你必须看看他们是如何做到的,因为它写在Netty的顶部。

链接断开了