netty(五)http服务

 

总体思路:

 

 

pipline总线:

    @Override
    public void initChannel(SocketChannel ch) throws Exception {

        ChannelPipeline pipeline = ch.pipeline();

        // decode 1 byte2http解码器
        pipeline.addLast(new HttpRequestDecoder());

        // encode last 1 http2byte编码器
        pipeline.addLast(new HttpResponseEncoder());
        pipeline.addLast(new HttpObjectAggregator(65535));

        // endoe last 2 body2full编码器
        pipeline.addLast(new BodyToResponseEncoder());

        // decode 2 full2body编码器
        pipeline.addLast(new RequestToBodyDecoder());

        // 业务处理Handler
        pipeline.addLast("httpServerHandler", handler);
    }

  

public class RequestToBodyDecoder extends MessageToMessageDecoder<FullHttpRequest> {

@Override
protected void decode(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest, List<Object> list) throws Exception {
// 内存泄漏 fullHttpRequest不再往下传递了,传递的是json
// ByteBuf msg = fullHttpRequest.content().retain();
ByteBuf msg = fullHttpRequest.content();

byte[] bs = new byte[msg.readableBytes()];
msg.readBytes(bs);
String json = new String(bs);

JSONObject jsonObject = null;

try {
jsonObject = JSONObject.parseObject(json);
} catch (Exception e) {
System.out.println("json error:" + json);

ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(ResponseMessage.genFail());
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if(!future.isSuccess()) {
future.cause().printStackTrace();
future.channel().close();
}
}
});
return;
}

if(null == jsonObject)
jsonObject = new JSONObject();

// 这样逻辑更通些
// channelHandlerContext.fireChannelRead(jsonObject);
// 这样也行,但是逻辑和性能都不如前者
// super.channelRead(channelHandlerContext, jsonObject);

list.add(jsonObject);
}

  

这个handler接收HttpRequestDecoder传送而来的FullHttpRequest,截取content部分byte(http body),反序列化为json字符串和json对象,传给下一个handler,如果参数不合法,则直接出站

 

@Sharable
public class HttpServerHandler extends SimpleChannelInboundHandler<JSONObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, JSONObject msg) throws Exception {

        System.out.println("收到客户端http请求: " + msg);

        msg.put("res", "收到了");

        ResponseMessage message = ResponseMessage.genSuccess().setResult(msg);

        ChannelFuture channelFuture = ctx.writeAndFlush(message);
     //   channelFuture.addListener(ChannelFutureListener.CLOSE);
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if(!future.isSuccess()) {
                    future.cause().printStackTrace();
                    future.channel().close();
                }
            }
        });
    }

  

主业务处理handler:接收参数json对象,简单处理后,形成ResponseMessage,出站

public class BodyToResponseEncoder extends MessageToMessageEncoder<ResponseMessage> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, ResponseMessage responseMessage, List<Object> list) throws Exception {

        String json = JSON.toJSONString(responseMessage);

        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.wrappedBuffer(json.getBytes("utf-8")));
        response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json;charset=UTF-8");
        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
        response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);

        // 下面2个支持跨域
        response.headers().set(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        response.headers().set(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_HEADERS, HttpHeaders.Names.CONTENT_TYPE);

        list.add(response);
    }
}

  

接收主handler的ResponseMessage,组合成HttpResponseEncoder需要的FullHttpResponse

 

调试一下:

curl  -H "Content-type: application/json" -X POST -d '{"orderId":"11112479","account":"DU984141"}' http://localhost:8990/

 

注意点:

1. 为什么BodyToResponseEncoder要在RequestToBodyDecoder之前?

RequestToBodyDecoder如果碰到不合法参数,直接返回出站,从该节点往上找OutBountHandler,此时如果没有BodyToResponseEncoder,ResponseMessage直接送到HttpResponseEncoder,它认不出报异常:

 这个问题在https://www.cnblogs.com/silyvin/articles/9504587.html 中已有讨论

 

4. 跨域相关结合:https://www.cnblogs.com/silyvin/p/9565896.html

 

5. HttpServerHandler使用了Sharable,具体参考:https://www.cnblogs.com/silyvin/p/9593368.html

 

6. 启动后第一次访问,用chrome时read被调用了2次,同样的情况:https://segmentfault.com/q/1010000009831091,

用postman  和 safari 时1次,正常

 

7 抓包:关于tcp delayedack实践(二)http

 

补充:

可以用

pipeline.addLast(new HttpServerCodec());

代替:

// decode 1 byte2http解码器
pipeline.addLast(new HttpRequestDecoder());

// encode last 1 http2byte编码器
pipeline.addLast(new HttpResponseEncoder());

来看一下HttpServerCodec:

public final class HttpServerCodec extends CombinedChannelDuplexHandler<HttpRequestDecoder, HttpResponseEncoder>

组合了HttpRequestDecoder和HttpResponseEncoder

posted on 2018-08-31 17:50  silyvin  阅读(702)  评论(0编辑  收藏  举报