Browse Source

don't use a sharable handler, prefer the netty FastThreadLocal

Luis Filipe dos Santos Neves 11 years ago
parent
commit
589535e8b1

+ 9 - 20
netty/src/main/java/hello/HelloServerHandler.java

@@ -3,7 +3,6 @@ package hello;
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
 import io.netty.buffer.Unpooled;
 import io.netty.channel.ChannelFutureListener;
 import io.netty.channel.ChannelFutureListener;
-import io.netty.channel.ChannelHandler;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.channel.SimpleChannelInboundHandler;
 import io.netty.channel.SimpleChannelInboundHandler;
 import io.netty.handler.codec.http.DefaultFullHttpResponse;
 import io.netty.handler.codec.http.DefaultFullHttpResponse;
@@ -13,6 +12,7 @@ import io.netty.handler.codec.http.HttpRequest;
 import io.netty.handler.codec.http.HttpResponseStatus;
 import io.netty.handler.codec.http.HttpResponseStatus;
 import io.netty.handler.codec.http.HttpVersion;
 import io.netty.handler.codec.http.HttpVersion;
 import io.netty.util.CharsetUtil;
 import io.netty.util.CharsetUtil;
+import io.netty.util.concurrent.FastThreadLocal;
 
 
 import java.text.DateFormat;
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 import java.text.SimpleDateFormat;
@@ -23,20 +23,16 @@ import java.util.concurrent.TimeUnit;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
 import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
 
 
[email protected]
 public class HelloServerHandler extends SimpleChannelInboundHandler<Object> {
 public class HelloServerHandler extends SimpleChannelInboundHandler<Object> {
-	private static final ThreadLocal<DateFormat> FORMAT = new ThreadLocal<DateFormat>() {
+    private static final FastThreadLocal<DateFormat> FORMAT = new FastThreadLocal<DateFormat>() {
         @Override
         @Override
         protected DateFormat initialValue() {
         protected DateFormat initialValue() {
             return new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
             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)));
-    private static final CharSequence contentLength = HttpHeaders.newEntity(
-            String.valueOf(CONTENT_BUFFER.readableBytes()));
+    private static final ByteBuf CONTENT_BUFFER = Unpooled.unreleasableBuffer(Unpooled.directBuffer().writeBytes("Hello, World!".getBytes(CharsetUtil.UTF_8)));
+    private static final CharSequence contentLength = HttpHeaders.newEntity(String.valueOf(CONTENT_BUFFER.readableBytes()));
 
 
     private static final CharSequence TYPE_PLAIN = HttpHeaders.newEntity("text/plain; charset=UTF-8");
     private static final CharSequence TYPE_PLAIN = HttpHeaders.newEntity("text/plain; charset=UTF-8");
     private static final CharSequence TYPE_JSON = HttpHeaders.newEntity("application/json; charset=UTF-8");
     private static final CharSequence TYPE_JSON = HttpHeaders.newEntity("application/json; charset=UTF-8");
@@ -76,8 +72,7 @@ public class HelloServerHandler extends SimpleChannelInboundHandler<Object> {
                     return;
                     return;
                 case "/json":
                 case "/json":
                     byte[] json = MAPPER.writeValueAsBytes(new Message("Hello, World!"));
                     byte[] json = MAPPER.writeValueAsBytes(new Message("Hello, World!"));
-                    writeResponse(ctx, request, Unpooled.wrappedBuffer(json), TYPE_JSON,
-                            String.valueOf(json.length));
+                    writeResponse(ctx, request, Unpooled.wrappedBuffer(json), TYPE_JSON, String.valueOf(json.length));
                     return;
                     return;
             }
             }
             FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, Unpooled.EMPTY_BUFFER, false);
             FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, Unpooled.EMPTY_BUFFER, false);
@@ -85,21 +80,16 @@ public class HelloServerHandler extends SimpleChannelInboundHandler<Object> {
         }
         }
     }
     }
 
 
-    private void writeResponse(ChannelHandlerContext ctx, HttpRequest request, ByteBuf buf,
-                               CharSequence contentType, CharSequence contentLength) {
+    private void writeResponse(ChannelHandlerContext ctx, HttpRequest request, ByteBuf buf, CharSequence contentType, CharSequence contentLength) {
         // Decide whether to close the connection or not.
         // Decide whether to close the connection or not.
         boolean keepAlive = HttpHeaders.isKeepAlive(request);
         boolean keepAlive = HttpHeaders.isKeepAlive(request);
         // Build the response object.
         // Build the response object.
-        FullHttpResponse response = new DefaultFullHttpResponse(
-                HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf, false);
+        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf, false);
         HttpHeaders headers = response.headers();
         HttpHeaders headers = response.headers();
         headers.set(CONTENT_TYPE_ENTITY, contentType);
         headers.set(CONTENT_TYPE_ENTITY, contentType);
         headers.set(SERVER_ENTITY, SERVER_NAME);
         headers.set(SERVER_ENTITY, SERVER_NAME);
         headers.set(DATE_ENTITY, date);
         headers.set(DATE_ENTITY, date);
-
-        if (keepAlive) {
-            headers.set(CONTENT_LENGTH_ENTITY, contentLength);
-        }
+        headers.set(CONTENT_LENGTH_ENTITY, contentLength);
 
 
         // Close the non-keep-alive connection after the write operation is done.
         // Close the non-keep-alive connection after the write operation is done.
         if (!keepAlive) {
         if (!keepAlive) {
@@ -110,8 +100,7 @@ public class HelloServerHandler extends SimpleChannelInboundHandler<Object> {
     }
     }
 
 
     @Override
     @Override
-    public void exceptionCaught(
-            ChannelHandlerContext ctx, Throwable cause) throws Exception {
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
         ctx.close();
         ctx.close();
     }
     }
 
 

+ 5 - 5
netty/src/main/java/hello/HelloServerInitializer.java

@@ -1,6 +1,5 @@
 package hello;
 package hello;
 
 
-import io.netty.channel.ChannelHandler;
 import io.netty.channel.ChannelInitializer;
 import io.netty.channel.ChannelInitializer;
 import io.netty.channel.ChannelPipeline;
 import io.netty.channel.ChannelPipeline;
 import io.netty.channel.socket.SocketChannel;
 import io.netty.channel.socket.SocketChannel;
@@ -10,15 +9,16 @@ import io.netty.handler.codec.http.HttpResponseEncoder;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ScheduledExecutorService;
 
 
 public class HelloServerInitializer extends ChannelInitializer<SocketChannel> {
 public class HelloServerInitializer extends ChannelInitializer<SocketChannel> {
-    private final ChannelHandler httpHandler;
-    public HelloServerInitializer(ScheduledExecutorService service) {
-        this.httpHandler = new HelloServerHandler(service);
+
+    private ScheduledExecutorService service;
+	public HelloServerInitializer(ScheduledExecutorService service) {
+        this.service = service;
     }
     }
     @Override
     @Override
     public void initChannel(SocketChannel ch) throws Exception {
     public void initChannel(SocketChannel ch) throws Exception {
         ChannelPipeline p = ch.pipeline();
         ChannelPipeline p = ch.pipeline();
         p.addLast("encoder", new HttpResponseEncoder());
         p.addLast("encoder", new HttpResponseEncoder());
         p.addLast("decoder", new HttpRequestDecoder(4096, 8192, 8192, false));
         p.addLast("decoder", new HttpRequestDecoder(4096, 8192, 8192, false));
-        p.addLast("handler", httpHandler);
+        p.addLast("handler", new HelloServerHandler(service));
     }
     }
 }
 }