首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Netty messageReceived超时

Netty messageReceived超时
EN

Stack Overflow用户
提问于 2016-10-17 23:50:07
回答 1查看 2K关注 0票数 5

我需要在我的messageReceived中使用channelRead0 (或Netty4.0的channelRead0)方法来在某个时间阈值之后超时。我尝试过读/写时间输出处理程序,但是当我的messageReceived处理时间超过超时时无法生成异常。以下是我尝试过的:

代码语言:javascript
运行
复制
public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline p = ch.pipeline();

        p.addLast(new HttpRequestDecoder());
        p.addLast(new HttpResponseEncoder());
        p.addLast(new HttpObjectAggregator(1048576));
        p.addLast(new HttpContentCompressor());
        p.addLast("readTimeoutHandler", new ReadTimeoutHandler(1));
        //p.addLast("idleTimeoutHandler", new IdleStateHandler(1, 1, 1));
        p.addLast(new HttpRequestHandler());
      }
  }



public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
  public static class Call implements Callable<Boolean> {
    public Boolean call() {
        for(long i = 0; i<100000000;i++){
            for(long j = 0; j<100;j++){

            }
        }
        return true;        
    }
 }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    System.out.println("** Exception caught **");
    if (cause instanceof ReadTimeoutException) {
       System.out.println("*** Request timed out ***");
    } 
    else if (cause instanceof WriteTimeoutException) {
           System.out.println("*** Request timed out on write ***");
        } 
    cause.printStackTrace();
    ctx.close();
  }

   @Override
    public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {

        FullHttpRequest request = this.request = (FullHttpRequest) msg;
        /*Callable<Boolean> callable = new Call();

    ScheduledExecutorService scheduler =
             Executors.newScheduledThreadPool(1);

    ScheduledFuture<Boolean> handle = scheduler.schedule(callable, 4, TimeUnit.SECONDS);
    boolean v  = handle.get();*/
    for(long i = 0; i<100000000;i++){
        for(long j = 0; j<100;j++){

        }
    }
    System.out.println("Wait done");

        try{
            CharSequence content = appController.handleRequest(
                    url,
                    ctx.channel().remoteAddress().toString(),
                    parseURL(url), reqBody);
            if(content!=null){
                writeResponse(ctx, HttpResponseStatus.OK, content);
            }
        }catch(AppRuntimeException e){
            CharSequence content = e.getMessage(); 
            if(content != null){
                OptHttpStatus status = e.getOptHttpStatus();
                writeResponse(ctx, HttpResponseStatus.valueOf(status.getCode()), content);
            }
        }

   private void writeResponse(ChannelHandlerContext ctx, HttpResponseStatus status, CharSequence content) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpUtil.isKeepAlive(request);

    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(
            HTTP_1_1, 
            status,
            Unpooled.copiedBuffer(content, CharsetUtil.UTF_8));
            //Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); 
    response.headers().set("Access-Control-Allow-Origin", "*");

    if (keepAlive) {
        //Add 'Content-Length' header only for a keep-alive connection.
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }
    // Write the response.
    ChannelFuture ch = ctx.writeAndFlush(response);

    if(!keepAlive){
        ch.addListener(ChannelFutureListener.CLOSE);
    }
}
    }

我在channelRead0方法中添加了一个冗余的for循环来模拟等待,以模拟较长的处理时间。但是没有生成超时异常。我也试着安排等待,但没有得到超时异常,您能提出任何解决方案吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-18 03:04:13

您想要做的事情有两个问题,一个是由于睡眠线程而不是通过调度使用异步延迟造成的,另一个是需要重新使用ReadTimeoutHandler.。

不要睡觉或阻塞

Thread.sleep不同,你为什么不尝试延迟安排你的工作呢?使用Netty,超时将发生在发送到睡眠的线程中,因此在超时检查发生之前,您仍然会编写响应。如果您安排延迟,那么线程就可以自由地检测超时并触发异常。

请记住,netty在多个通道上使用一个IO线程,因此您不应该在该线程中执行任何阻塞/同步工作。Thread.sleep、繁忙循环、同步调用、阻塞调用(例如Future.get()不应该在IO线程中执行,因为这会影响其他通道的性能。

您可以使用 上下文 来获取一个执行器来安排您延迟的工作。

代码语言:javascript
运行
复制
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) {
    ctx.executor().schedule(new Runnable() {
        @Override
        public void run() {
            // Put your try/catch in here
        }
    }, 5000, TimeUnit.MILLISECONDS);
}

如果你必须打个阻塞电话

如果您无法避免进行阻塞调用或进行一些激烈的处理,那么在添加处理处理程序时使用不同的EventExecutorGroup,以允许从IO工作线程异步完成该工作。一定要为它提供足够的线程,以满足您预期的工作负载和连接数量。

下面的示例代码应该与您的Thread.sleep或繁忙循环一起工作。只需确保用满足您需要的数字来定义/替换OFFLOAD_THREADS。

代码语言:javascript
运行
复制
public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {
    private final EventExecutorGroup executors = new DefaultEventExecutorGroup(OFFLOAD_THREADS);
    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline p = ch.pipeline();

        p.addLast(new HttpRequestDecoder());
        p.addLast(new HttpResponseEncoder());
        p.addLast(new HttpObjectAggregator(1048576));
        p.addLast(new HttpContentCompressor());
        p.addLast("idleTimeoutHandler", new IdleStateHandler(0, 1, 0));
        p.addLast(executors, new HttpRequestHandler());
    }
}

使用IdleStateHandler

如果写入时间太长,WriteTimeoutHandler就意味着超时。它甚至不会开始计时,直到你开始你的第一次写作。看起来,您甚至在开始编写之前就试图造成延迟,所以WriteTimeoutHandler不会为您触发,即使您按照上面的建议停止使用睡眠。

如果您真的想要超时,您需要多长时间才能开始编写,那么您应该使用IdleStateHandler并处理它触发的用户事件。与WriteTimeoutHandler不同的是,当通道激活时,IdleStateHandler将开始计数,而不是等待写入启动,因此,如果处理时间过长(但只在执行处理异步时),它将触发。

确保在使用IdleStateHandler时捕获用户事件并对其作出反应

代码语言:javascript
运行
复制
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt == IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT) {
        // Handle the event here
    }
    else {
        super.userEventTriggered(ctx, evt);
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40097391

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档