Retry requests with Netty HTTP client

Viewed 1265

How should one retry HTTP requests in a Netty-based HTTP client?

Consider the following handler, which attempts to retry the HTTP request after 1 second if HTTP response code 503 is received:

public class RetryChannelHandler extends ChannelDuplexHandler {
    List<HttpObject> requestParts;

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (msg instanceof HttpRequest) {
            requestParts = new ArrayList<>();
            requestParts.add((HttpRequest)msg);
        } else if (msg instanceof HttpObject) {
            requestParts.add((HttpObject)msg);
        }

        super.write(ctx, msg, promise);
    }

    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpResponse) {
            HttpResponse res = (HttpResponse)msg;
            if (res.status().code() == 503) {
                ctx.executor().schedule(new Runnable() {
                    @Override
                    public void run() {
                        for (HttpObject obj : requestParts) {
                            ctx.channel().write(obj);
                        }
                    }
                }, 1000, TimeUnit.MILLISECONDS);
            } else {
                super.channelRead(ctx, msg);
            }
        } else {
            super.channelRead(ctx, msg);
        }
    }
}

When I write to the channel in this example, the other handlers in the pipeline see the HttpObjects, but the HttpRequest is not actually performed again-- only one HttpResponse is ever received.

I think I'm simply misusing Channel in this case, and I need to create a new Channel (representing a new connection to the server) to perform the retry. What's not clear to me is how to create that new Channel from the context of the Handler, and whether I'm really in the right layer of Netty to be doing this kind of logic.

Any guidance on how to achieve the kind of behavior I'm describing would be appreciated.

1 Answers
Related