Browse Source

Merge pull request #917 from lneves/master

netty: use the default settings for the PooledByteBufAllocator

The tests seem to pass so I'll merge this right in!
mcocciaTE 11 years ago
parent
commit
0dcebd3150

+ 51 - 49
netty/src/main/java/hello/HelloServerHandler.java

@@ -25,10 +25,10 @@ import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
 
 public class HelloServerHandler extends SimpleChannelInboundHandler<Object> {
     private static final FastThreadLocal<DateFormat> FORMAT = new FastThreadLocal<DateFormat>() {
-        @Override
-        protected DateFormat initialValue() {
-            return new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
-        }
+	@Override
+	protected DateFormat initialValue() {
+	    return new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
+	}
     };
 
     private static final ByteBuf CONTENT_BUFFER = Unpooled.unreleasableBuffer(Unpooled.directBuffer().writeBytes("Hello, World!".getBytes(CharsetUtil.UTF_8)));
@@ -42,70 +42,72 @@ public class HelloServerHandler extends SimpleChannelInboundHandler<Object> {
     private static final CharSequence CONTENT_LENGTH_ENTITY = HttpHeaders.newEntity(HttpHeaders.Names.CONTENT_LENGTH);
     private static final CharSequence SERVER_ENTITY = HttpHeaders.newEntity(HttpHeaders.Names.SERVER);
     private static final ObjectMapper MAPPER;
-    
-    static{
-    	MAPPER = new ObjectMapper();
-    	MAPPER.registerModule(new AfterburnerModule());
+
+    static {
+	MAPPER = new ObjectMapper();
+	MAPPER.registerModule(new AfterburnerModule());
     }
-    
+
     private volatile CharSequence date = HttpHeaders.newEntity(FORMAT.get().format(new Date()));
 
     HelloServerHandler(ScheduledExecutorService service) {
-        service.scheduleWithFixedDelay(new Runnable() {
-            private final DateFormat format = FORMAT.get();
-            @Override
-            public void run() {
-                date = HttpHeaders.newEntity(format.format(new Date()));
-            }
-        }, 1000, 1000, TimeUnit.MILLISECONDS);
+	service.scheduleWithFixedDelay(new Runnable() {
+	    private final DateFormat format = FORMAT.get();
+
+	    @Override
+	    public void run() {
+		date = HttpHeaders.newEntity(format.format(new Date()));
+	    }
+	}, 1000, 1000, TimeUnit.MILLISECONDS);
 
     }
 
     @Override
     public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
-        if (msg instanceof HttpRequest) {
-            HttpRequest request = (HttpRequest) msg;
-            String uri = request.getUri();
-            switch (uri) {
-                case "/plaintext":
-                    writeResponse(ctx, request, CONTENT_BUFFER.duplicate(), TYPE_PLAIN, contentLength);
-                    return;
-                case "/json":
-                    byte[] json = MAPPER.writeValueAsBytes(new Message("Hello, World!"));
-                    writeResponse(ctx, request, Unpooled.wrappedBuffer(json), TYPE_JSON, String.valueOf(json.length));
-                    return;
-            }
-            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, Unpooled.EMPTY_BUFFER, false);
-            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
-        }
+	if (msg instanceof HttpRequest) {
+	    HttpRequest request = (HttpRequest) msg;
+	    String uri = request.getUri();
+	    switch (uri) {
+	    case "/plaintext":
+		writeResponse(ctx, request, CONTENT_BUFFER.duplicate(), TYPE_PLAIN, contentLength);
+		return;
+	    case "/json":
+		byte[] json = MAPPER.writeValueAsBytes(new Message("Hello, World!"));
+		writeResponse(ctx, request, Unpooled.wrappedBuffer(json), TYPE_JSON, String.valueOf(json.length));
+		return;
+	    }
+	    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, Unpooled.EMPTY_BUFFER, false);
+	    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
+	}
     }
 
     private void writeResponse(ChannelHandlerContext ctx, HttpRequest request, ByteBuf buf, CharSequence contentType, CharSequence contentLength) {
-        // Decide whether to close the connection or not.
-        boolean keepAlive = HttpHeaders.isKeepAlive(request);
-        // Build the response object.
-        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf, false);
-        HttpHeaders headers = response.headers();
-        headers.set(CONTENT_TYPE_ENTITY, contentType);
-        headers.set(SERVER_ENTITY, SERVER_NAME);
-        headers.set(DATE_ENTITY, date);
-        headers.set(CONTENT_LENGTH_ENTITY, contentLength);
-
-        // Close the non-keep-alive connection after the write operation is done.
-        if (!keepAlive) {
-            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
-        } else {
-            ctx.write(response, ctx.voidPromise());
-        }
+	// Decide whether to close the connection or not.
+	boolean keepAlive = HttpHeaders.isKeepAlive(request);
+	// Build the response object.
+	FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf, false);
+	HttpHeaders headers = response.headers();
+	headers.set(CONTENT_TYPE_ENTITY, contentType);
+	headers.set(SERVER_ENTITY, SERVER_NAME);
+	headers.set(DATE_ENTITY, date);
+	headers.set(CONTENT_LENGTH_ENTITY, contentLength);
+
+	// Close the non-keep-alive connection after the write operation is
+	// done.
+	if (!keepAlive) {
+	    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
+	} else {
+	    ctx.write(response, ctx.voidPromise());
+	}
     }
 
     @Override
     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
-        ctx.close();
+	ctx.close();
     }
 
     @Override
     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
-        ctx.flush();
+	ctx.flush();
     }
 }

+ 8 - 6
netty/src/main/java/hello/HelloServerInitializer.java

@@ -11,14 +11,16 @@ import java.util.concurrent.ScheduledExecutorService;
 public class HelloServerInitializer extends ChannelInitializer<SocketChannel> {
 
     private ScheduledExecutorService service;
-	public HelloServerInitializer(ScheduledExecutorService service) {
-        this.service = service;
+
+    public HelloServerInitializer(ScheduledExecutorService service) {
+	this.service = service;
     }
+
     @Override
     public void initChannel(SocketChannel ch) throws Exception {
-        ChannelPipeline p = ch.pipeline();
-        p.addLast("encoder", new HttpResponseEncoder());
-        p.addLast("decoder", new HttpRequestDecoder(4096, 8192, 8192, false));
-        p.addLast("handler", new HelloServerHandler(service));
+	ChannelPipeline p = ch.pipeline();
+	p.addLast("encoder", new HttpResponseEncoder());
+	p.addLast("decoder", new HttpRequestDecoder(4096, 8192, 8192, false));
+	p.addLast("handler", new HelloServerHandler(service));
     }
 }

+ 33 - 36
netty/src/main/java/hello/HelloWebServer.java

@@ -14,56 +14,53 @@ import io.netty.channel.socket.nio.NioServerSocketChannel;
 import io.netty.util.ResourceLeakDetector;
 import io.netty.util.ResourceLeakDetector.Level;
 
-
 public class HelloWebServer {
-	private static int IO_THREADS = Runtime.getRuntime().availableProcessors() * 2;
+
     static {
-        ResourceLeakDetector.setLevel(Level.DISABLED);
+	ResourceLeakDetector.setLevel(Level.DISABLED);
     }
 
     private final int port;
 
     public HelloWebServer(int port) {
-        this.port = port;
+	this.port = port;
     }
 
     public void run() throws Exception {
-		// Configure the server.
-		
-		if (Epoll.isAvailable()) {
-			doRun( new EpollEventLoopGroup(), EpollServerSocketChannel.class);
-		}
-		else {
-			doRun(new NioEventLoopGroup(), NioServerSocketChannel.class);
-		} 
+	// Configure the server.
+
+	if (Epoll.isAvailable()) {
+	    doRun(new EpollEventLoopGroup(), EpollServerSocketChannel.class);
+	} else {
+	    doRun(new NioEventLoopGroup(), NioServerSocketChannel.class);
+	}
     }
-    
-	private void doRun(EventLoopGroup loupGroup, Class<? extends ServerChannel> serverChannelClass) throws InterruptedException	{
-		try {
-			ServerBootstrap b = new ServerBootstrap();
-			b.option(ChannelOption.SO_BACKLOG, 1024);
-			b.option(ChannelOption.SO_REUSEADDR, true);
-			b.group(loupGroup).channel(serverChannelClass).childHandler(new HelloServerInitializer(loupGroup.next()));			
-            b.option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
-            b.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true, IO_THREADS, IO_THREADS, 8192, 11));
-            b.childOption(ChannelOption.SO_REUSEADDR, true);
-            b.childOption(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
 
-			Channel ch = b.bind(port).sync().channel();
-			ch.closeFuture().sync();
-		}
-		finally {
-			loupGroup.shutdownGracefully().sync();
-		}
+    private void doRun(EventLoopGroup loupGroup, Class<? extends ServerChannel> serverChannelClass) throws InterruptedException {
+	try {
+	    ServerBootstrap b = new ServerBootstrap();
+	    b.option(ChannelOption.SO_BACKLOG, 1024);
+	    b.option(ChannelOption.SO_REUSEADDR, true);
+	    b.group(loupGroup).channel(serverChannelClass).childHandler(new HelloServerInitializer(loupGroup.next()));
+	    b.option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
+	    b.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
+	    b.childOption(ChannelOption.SO_REUSEADDR, true);
+	    b.childOption(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
+
+	    Channel ch = b.bind(port).sync().channel();
+	    ch.closeFuture().sync();
+	} finally {
+	    loupGroup.shutdownGracefully().sync();
 	}
+    }
 
     public static void main(String[] args) throws Exception {
-        int port;
-        if (args.length > 0) {
-            port = Integer.parseInt(args[0]);
-        } else {
-            port = 8080;
-        }
-        new HelloWebServer(port).run();
+	int port;
+	if (args.length > 0) {
+	    port = Integer.parseInt(args[0]);
+	} else {
+	    port = 8080;
+	}
+	new HelloWebServer(port).run();
     }
 }

+ 9 - 9
netty/src/main/java/hello/Message.java

@@ -1,15 +1,15 @@
 package hello;
 
 public class Message {
-	
-	private final String message;
 
-	public Message(String message) {
-		super();
-		this.message = message;
-	}
+    private final String message;
 
-	public String getMessage() {
-		return message;
-	}
+    public Message(String message) {
+	super();
+	this.message = message;
+    }
+
+    public String getMessage() {
+	return message;
+    }
 }