HelloServerHandler.java 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. package hello;
  2. import java.text.DateFormat;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5. import java.util.concurrent.ScheduledExecutorService;
  6. import java.util.concurrent.TimeUnit;
  7. import com.fasterxml.jackson.core.JsonProcessingException;
  8. import com.fasterxml.jackson.databind.ObjectMapper;
  9. import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
  10. import io.netty.buffer.ByteBuf;
  11. import io.netty.buffer.Unpooled;
  12. import io.netty.channel.ChannelFutureListener;
  13. import io.netty.channel.ChannelHandlerContext;
  14. import io.netty.channel.ChannelInboundHandlerAdapter;
  15. import io.netty.handler.codec.http.DefaultFullHttpResponse;
  16. import io.netty.handler.codec.http.FullHttpResponse;
  17. import io.netty.handler.codec.http.HttpRequest;
  18. import io.netty.util.AsciiString;
  19. import io.netty.util.CharsetUtil;
  20. import io.netty.util.ReferenceCountUtil;
  21. import io.netty.util.concurrent.FastThreadLocal;
  22. import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
  23. import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
  24. import static io.netty.handler.codec.http.HttpHeaderNames.DATE;
  25. import static io.netty.handler.codec.http.HttpHeaderNames.SERVER;
  26. import static io.netty.handler.codec.http.HttpHeaderValues.APPLICATION_JSON;
  27. import static io.netty.handler.codec.http.HttpHeaderValues.TEXT_PLAIN;
  28. import static io.netty.handler.codec.http.HttpResponseStatus.*;
  29. import static io.netty.handler.codec.http.HttpVersion.*;
  30. public class HelloServerHandler extends ChannelInboundHandlerAdapter {
  31. private static final FastThreadLocal<DateFormat> FORMAT = new FastThreadLocal<DateFormat>() {
  32. @Override
  33. protected DateFormat initialValue() {
  34. return new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
  35. }
  36. };
  37. private static ObjectMapper newMapper() {
  38. ObjectMapper m = new ObjectMapper();
  39. m.registerModule(new AfterburnerModule());
  40. return m;
  41. }
  42. private static Message newMsg() {
  43. return new Message("Hello, World!");
  44. }
  45. private static int jsonLen() {
  46. try {
  47. return newMapper().writeValueAsBytes(newMsg()).length;
  48. } catch (JsonProcessingException e) {
  49. throw new RuntimeException(e);
  50. }
  51. }
  52. private static final byte[] STATIC_PLAINTEXT = "Hello, World!".getBytes(CharsetUtil.UTF_8);
  53. private static final int STATIC_PLAINTEXT_LEN = STATIC_PLAINTEXT.length;
  54. private static final ByteBuf PLAINTEXT_CONTENT_BUFFER = Unpooled.unreleasableBuffer(Unpooled.directBuffer().writeBytes(STATIC_PLAINTEXT));
  55. private static final CharSequence PLAINTEXT_CLHEADER_VALUE = AsciiString.cached(String.valueOf(STATIC_PLAINTEXT_LEN));
  56. private static final CharSequence JSON_CLHEADER_VALUE = AsciiString.cached(String.valueOf(jsonLen()));
  57. private static final CharSequence SERVER_NAME = AsciiString.cached("Netty");
  58. private static final ObjectMapper MAPPER = newMapper();
  59. private volatile CharSequence date = new AsciiString(FORMAT.get().format(new Date()));
  60. HelloServerHandler(ScheduledExecutorService service) {
  61. service.scheduleWithFixedDelay(new Runnable() {
  62. private final DateFormat format = FORMAT.get();
  63. @Override
  64. public void run() {
  65. date = new AsciiString(format.format(new Date()));
  66. }
  67. }, 1000, 1000, TimeUnit.MILLISECONDS);
  68. }
  69. @Override
  70. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  71. if (msg instanceof HttpRequest) {
  72. try {
  73. HttpRequest request = (HttpRequest) msg;
  74. process(ctx, request);
  75. } finally {
  76. ReferenceCountUtil.release(msg);
  77. }
  78. } else {
  79. ctx.fireChannelRead(msg);
  80. }
  81. }
  82. private void process(ChannelHandlerContext ctx, HttpRequest request) throws Exception {
  83. String uri = request.uri();
  84. switch (uri) {
  85. case "/plaintext":
  86. writePlainResponse(ctx, PLAINTEXT_CONTENT_BUFFER.duplicate());
  87. return;
  88. case "/json":
  89. byte[] json = MAPPER.writeValueAsBytes(newMsg());
  90. writeJsonResponse(ctx, Unpooled.wrappedBuffer(json));
  91. return;
  92. }
  93. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND, Unpooled.EMPTY_BUFFER, false);
  94. ctx.write(response).addListener(ChannelFutureListener.CLOSE);
  95. }
  96. private void writePlainResponse(ChannelHandlerContext ctx, ByteBuf buf) {
  97. ctx.write(makeResponse(buf, TEXT_PLAIN, PLAINTEXT_CLHEADER_VALUE), ctx.voidPromise());
  98. }
  99. private void writeJsonResponse(ChannelHandlerContext ctx, ByteBuf buf) {
  100. ctx.write(makeResponse(buf, APPLICATION_JSON, JSON_CLHEADER_VALUE), ctx.voidPromise());
  101. }
  102. private FullHttpResponse makeResponse(ByteBuf buf, CharSequence contentType, CharSequence contentLength) {
  103. final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buf, false);
  104. response.headers()
  105. .set(CONTENT_TYPE, contentType)
  106. .set(SERVER, SERVER_NAME)
  107. .set(DATE, date)
  108. .set(CONTENT_LENGTH, contentLength);
  109. return response;
  110. }
  111. @Override
  112. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  113. ctx.close();
  114. }
  115. @Override
  116. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  117. ctx.flush();
  118. }
  119. }