Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to route requests based on URI in Netty?

Tags:

java

netty

I'm new to Netty and to get more familiar with it I'm working on building a simple HTTP server. One thing I want to do is deal with routing based on the URI. I looked around for examples and found a few approaches and wanted to see which made the most sense.

  1. Have a "route" handler that will add/remove others based on the URI in the HTTPMessage. This seems inefficient if I have to do this for every single request.

  2. Have the "route" handler wrap the HTTPMessage and HTTPContent inside another object that will then be passed in to the appropriate handler. For example, I can have an InfoHandler that extends SimpleChannelInboundHandler and the router InfoHTTPRequest object. This way the pipeline stays fixed and I'm not changing it on the fly - I am creating more objects though.

  3. Have a single route handler that just has methods to handle the different endpoints. I can have a handleInfo method, a handleUpdate method, etc with each of those having their own implementation and referencing their own dependencies.

PS - I'm using Netty 4.0 and most of my understanding has come from various online research and reading the Netty In Action book.

like image 213
Dan Goldin Avatar asked Mar 03 '14 17:03

Dan Goldin


1 Answers

I use a fixed pipeline which is only responsible for decoding/encoding requests/responses (and optional aggregation, compression, static headers, etc).

The final handler in the pipeline passes off to a configurable RequestResolver (generic to support types other than HTTP) which looks a little like:

public interface RequestResolver<T> {
    void execute(@Nonnull ChannelHandlerContext ctx, @Nonnull T req);
}

The request resolver is responsible for deciding how to handle the request (i.e. routing if necessary) and generally passes off to one or more actions that have been registered on it, or returns a 404. It doesn't have anything to do with the pipeline so much, other than it takes a ctx with which to queue responses.

I started using Netty 4 right back when it was alpha-01 and there was no routing framework plugins available, so I wrote my own RequestResolver in Java, more recently I've another written in Clojure which re-uses the Clout routing from Compojure.

like image 147
Derek Troy-West Avatar answered Nov 17 '22 21:11

Derek Troy-West