2013-03-28 6 views
5

Netty를 처음 접했고 클라이언트에서 요청을 받고 요청을 다른 서버로 전달한 다음 간단한 응답을 원래 요청에 대한 응답으로 복사하는 간단한 http 프록시 서버를 만들기 위해이 서버를 사용하려고합니다. 추가 요구 사항 중 하나는 시간 제한을 지원할 수 있기 때문에 프록시 서버가 응답하는 데 너무 오래 걸리면 프록시가 자동으로 응답하고 프록시 서버에 대한 연결을 닫을 수 있습니다.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의 상단에 기록 된대로 그들은 그것을 어떻게 볼 LittleProxy 보는 것

답변

4

.

+1

링크가 깨졌습니다. –

관련 문제