Skip to content

Instantly share code, notes, and snippets.

@jbrisbin
Last active December 25, 2015 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jbrisbin/7043968 to your computer and use it in GitHub Desktop.
Save jbrisbin/7043968 to your computer and use it in GitHub Desktop.
Example of using Reactor to serve HTTP requests using Netty's built-in HTTP codec.
public class NettyHttpServerSocketOptions extends NettyServerSocketOptions {
@Override
public final Consumer<ChannelPipeline> pipelineConfigurer() {
return new Consumer<ChannelPipeline>() {
@Override
public void accept(ChannelPipeline pipeline) {
pipeline.addLast(new HttpRequestDecoder());
pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
pipeline.addLast(new HttpResponseEncoder());
}
};
}
}
TcpServer<HttpRequest, HttpResponse> server = new TcpServerSpec<HttpRequest, HttpResponse>(NettyTcpServer.class)
.env(env)
.listen(port)
.options(new NettyHttpServerSocketOptions())
.consume(new Consumer<TcpConnection<HttpRequest, HttpResponse>>() {
@Override
public void accept(final TcpConnection<HttpRequest, HttpResponse> conn) {
// Use the Stream API rather than consuming messages directly
conn.in()
.map(new Function<HttpRequest, HttpResponse>() {
@Override
public HttpResponse apply(HttpRequest req) {
ByteBuf buf = Unpooled.copiedBuffer("Hello World!".getBytes());
int len = buf.readableBytes();
DefaultFullHttpResponse resp = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,
buf
);
HttpHeaders hdrs = resp.headers();
hdrs.set(HttpHeaders.Names.CONTENT_LENGTH, len);
hdrs.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
hdrs.set(HttpHeaders.Names.CONNECTION, "Keep-Alive");
// NOTE: This would be a fully-formed, "proper" HTTP 1.1 response
// if we added Date and Server headers.
// If we're just writing the response, then we can return it from a Function.
// We only need to send responses later if we're doing long work of some kind
// like submitting a batch job to a worker queue.
return resp;
}
})
// the output of a connection is also a Consumer
.consume(conn.out());
}
})
.get();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment