首页  

基于netty的RESTFUL框架     所属分类 netty 浏览量 986
服务启动入口 RestServerTest

完整代码
https://gitee.com/dyyx/nettyrest/blob/master/src/test/java/org/dyyx/nrest/RestServerTest.java

netty 部分 核心代码
https://gitee.com/dyyx/nettyrest/blob/master/src/main/java/org/dyyx/nrest/core/HandlerInitializer.java




org.dyyx.nrest.core.WebServer.start
// 注册所有REST Controller
new ControllerFactory().registerController(this.controllerBasePackage);
org.dyyx.nrest.rest.mapping.ControllerMappingRegistry.registerBean

src/test/java/org/dyyx/nrest/RestServerTest.java





@Override
protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("decoder", new HttpRequestDecoder());
        pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength));
        pipeline.addLast("encoder", new HttpResponseEncoder());
        // 启用gzip(由于使用本地存储文件,不能启用gzip)
        //pipeline.addLast(new HttpContentCompressor(1));
        pipeline.addLast(new ChunkedWriteHandler());
        // 将HttpRequestHandler放在业务线程池中执行,避免阻塞worker线程
        pipeline.addLast(eventExecutorGroup, "httpRequestHandler", new HttpRequestHandler());
}


业务线程池
ChannelPipeline addLast(EventExecutorGroup group, String name, ChannelHandler handler);  
group the which will be used to execute the  ChannelHandler


ChannelInboundHandler按照注册的先后顺序执行
ChannelOutboundHandler按照注册的先后顺序逆序执行
InboundHandler :  HttpRequestDecoder HttpObjectAggregator HttpHandler 
OutboundHandler:  HttpContentCompressor HttpResponseEncoder

Handler 使用 注意点
ChannelInboundHandler之间的传递  ctx.fireChannelRead(msg) 
调用ctx.write(msg) 传递到ChannelOutboundHandler
ctx.write() 后,需要调用flush()方法才能立即执行
ChannelOutboundHandler 注册时需要放在最后一个ChannelInboundHandler之前,否则无法传递到ChannelOutboundHandler
Handler的消费处理放在最后一个处理


telnet 使用业务线程池的例子
https://gitee.com/dyyx/netty4demo/blob/master/src/main/java/dyyx/telnet/TelnetServerHandlerUseThreadPool.java
https://gitee.com/dyyx/netty4demo/blob/master/src/main/java/dyyx/telnetclient/TelnetClient.java


HelloController @RestController public class HelloController { @GetMapping("/hello") @JsonResponse public ResponseEntity<String> hello() { return ResponseEntity.ok().build("hello,netty-rest,"+LocalDateTime.now()); }
最简单的http server https://gitee.com/dyyx/netty4demo/blob/master/src/main/java/dyyx/http/HttpServerInit.java HttpServerInit @Override public void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); // HTTP 服务的解码器 p.addLast(new HttpServerCodec()); // HTTP 消息的合并处理 p.addLast(new HttpObjectAggregator(2048)); // p.addLast(new HttpServerHandler()); p.addLast(new HttpServerHandler2()); }
netty4耗时业务处理实例 netty耗时任务处理

上一篇     下一篇
dubbo获取线程池等信息

dubbo SPI 机制简介

dubbo各个模块简介

Java动态代理InvocationHandler例子

Linux常用命令汇总

Java类加载过程