2013-03-28 18 views
5

Nettyを初めて使っていて、クライアントから要求を受け取り、別のサーバーに要求を転送し、元の要求の応答に応答をコピーする単純なhttpプロキシサーバーを作成するのに使用します。追加の要件の1つは、プロキシサーバーが応答に時間がかかり過ぎると、プロキシがそれ自身で応答し、プロキシサーバーへの接続を閉じるように、タイムアウトをサポートできることです。Nettyを使用してhttpプロキシサーバーを構築する簡単な方法は?

私はすでにJettyを使ってこのようなアプリケーションを実装していますが、Jettyでは、インバウンドリクエストがブロックされないようにするにはスレッドを多用する必要があります(これはメモリやCPUをほとんど使用しない軽量アプリケーションですが、プロキシされたサーバーは、トラフィックのバーストがプロキシサーバーのキューイングを引き起こすか、またはスレッドが多すぎるほど十分に高いです。

私の理解によれば、Nettyを使用して、各ステージが少量の計算を実行し、スレッドを解放し、パイプラインの次のステージが実行される準備ができるまで待機します。

私の質問は、そのようなアプリケーションの簡単な例はありますか?私がこれまでに持っているのは、基本的なNettyチュートリアル用のサーバーコードを単純に変更したものですが、クライアントに対するサポートはすべてありません。私はネットクライアントのチュートリアルを見ましたが、シンプルなプロキシアプリケーションを作成するために2つのコードを混ぜ合わせる方法がわかりません。

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(); 
    } 
} 

答えて

4

あなたはそれが網状の上に書かれているとして、彼らはそれをやったかを確認するためにLittleProxyを見なければならないでしょう。

+1

リンクが壊れています –

関連する問題