Browse Source

青涩知夏->完善配置

青涩知夏 4 years ago
parent
commit
1f03cab810

+ 1 - 4
src/main/java/cn/nosum/common/http/entity/Request.java

@@ -1,11 +1,8 @@
 package cn.nosum.common.http.entity;
 
 
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandlerContext;
 import io.netty.handler.codec.http.FullHttpRequest;
 import io.netty.handler.codec.http.HttpMethod;
-import io.netty.handler.codec.http.HttpRequest;
 import io.netty.handler.codec.http.QueryStringDecoder;
 import io.netty.handler.codec.http.multipart.Attribute;
 import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
@@ -31,7 +28,7 @@ public class Request {
     private void initParam(FullHttpRequest req){
         try{
             HttpMethod method = req.method();
-            paramMap=new HashMap<>();
+            paramMap = new HashMap<>();
             if (HttpMethod.GET == method) {
                 // GET请求
                 QueryStringDecoder decoder = new QueryStringDecoder(req.uri());

+ 5 - 1
src/main/java/cn/nosum/common/util/NettyFileUtil.java

@@ -29,7 +29,7 @@ public class NettyFileUtil {
         }
         try (FileOutputStream fileOutputStream = new FileOutputStream(file,append);
              FileChannel fileChannel = fileOutputStream.getChannel()) {
-            ByteBuffer byteBuffer = ByteBuffer.allocate(BYTE_BUFFER_LENGTH+LINE_SEPARATOR.length());
+            ByteBuffer byteBuffer = ByteBuffer.allocate(getLength(data.length())+LINE_SEPARATOR.length());
             int i = 0;
             int length = data.getBytes().length;
             // 一次性读取完毕
@@ -106,4 +106,8 @@ public class NettyFileUtil {
             logger.error("文件复制错误,错误原因 :{0}", e);
         }
     }
+
+    public static int getLength(Integer length){
+        return BYTE_BUFFER_LENGTH>length?length:BYTE_BUFFER_LENGTH;
+    }
 }

+ 30 - 29
src/main/java/cn/nosum/gateway/container/NettyGateWayContainer.java

@@ -5,6 +5,7 @@ import cn.nosum.common.util.Convert;
 import cn.nosum.common.util.PropertiesUtil;
 import cn.nosum.gateway.handler.build.HandlerProvider;
 import io.netty.bootstrap.ServerBootstrap;
+import io.netty.buffer.PooledByteBufAllocator;
 import io.netty.channel.*;
 import io.netty.channel.nio.NioEventLoopGroup;
 import io.netty.channel.socket.nio.NioServerSocketChannel;
@@ -14,34 +15,34 @@ import org.slf4j.LoggerFactory;
 
 @Adaptive
 public class NettyGateWayContainer implements GateWayContainer {
-	Logger logger= LoggerFactory.getLogger(NettyGateWayContainer.class);
-	private int port = Convert.toInt(PropertiesUtil.getProperty("container.port"));
-	public void start(){
-		// Boss线程
-		EventLoopGroup bossGroup = new NioEventLoopGroup();
-		// Worker线程
-		EventLoopGroup workerGroup = new NioEventLoopGroup();
-		try {
-			ServerBootstrap server = new ServerBootstrap();
-			server.group(bossGroup, workerGroup)
-					.channel(NioServerSocketChannel.class)
-					// 子线程处理类 , Handler
-					.childHandler(HandlerProvider.newHandlerChannel())
-					// 针对主线程的配置 分配线程最大数量 128
-					.option(ChannelOption.SO_BACKLOG, 128)
-					// 针对子线程的配置 保持长连接
-					.childOption(ChannelOption.SO_KEEPALIVE, true);
+    Logger logger = LoggerFactory.getLogger(NettyGateWayContainer.class);
+    private int port = Convert.toInt(PropertiesUtil.getProperty("container.port"));
 
-			// 启动服务器
-			ChannelFuture f = server.bind(port).sync();
-			logger.debug("NettyGateWayContainer启动成功,访问端口号是:{}",port);
-			f.channel().closeFuture().sync();
-		}catch (Exception e){
-			e.printStackTrace();
-		}finally {
-			// 关闭线程池
-			bossGroup.shutdownGracefully();
-			workerGroup.shutdownGracefully();
-		}
-	}
+    public void start() {
+        // Boss线程
+        EventLoopGroup bossGroup = new NioEventLoopGroup(6);
+        // Worker线程
+        EventLoopGroup workerGroup = new NioEventLoopGroup(12);
+        try {
+            ServerBootstrap server = new ServerBootstrap();
+            server.group(bossGroup, workerGroup);
+            server.channel(NioServerSocketChannel.class);
+            server.childHandler(HandlerProvider.newHandlerChannel());
+            server.option(ChannelOption.SO_BACKLOG, 128);
+            server.option(ChannelOption.TCP_NODELAY,true);
+            server.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
+            server.childOption(ChannelOption.TCP_NODELAY, true);
+            // server.childOption(ChannelOption.SO_KEEPALIVE, true);
+            // 启动服务器
+            ChannelFuture f = server.bind(port).sync();
+            logger.debug("NettyGateWayContainer启动成功,访问端口号是:{}", port);
+            f.channel().closeFuture().sync();
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            // 关闭线程池
+            bossGroup.shutdownGracefully();
+            workerGroup.shutdownGracefully();
+        }
+    }
 }

+ 0 - 27
src/main/java/cn/nosum/gateway/handler/FileProcessHandler.java

@@ -1,27 +0,0 @@
-package cn.nosum.gateway.handler;
-
-import cn.nosum.common.constant.CommonConstants;
-import cn.nosum.common.http.entity.Context;
-import cn.nosum.common.util.LinuxCmd;
-import cn.nosum.common.util.NettyFileUtil;
-import cn.nosum.common.util.PropertiesUtil;
-import com.alibaba.fastjson.JSON;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.SimpleChannelInboundHandler;
-
-public class FileProcessHandler extends SimpleChannelInboundHandler<Context> {
-
-    @Override
-    protected void channelRead0(ChannelHandlerContext ctx, Context context) throws Exception {
-        NettyFileUtil.dataToFile(JSON.toJSONString(context.getRequest().getParameters()),
-                PropertiesUtil.getProperty(CommonConstants.REQUEST_FILE_SAVE_FOLDER_NAME) + context.getRequest().getUrl(),
-                true);
-        context.setResult(LinuxCmd.executeLinuxCmd("stat "+context.getRequest().getUrl()));
-        ctx.fireChannelRead(context);
-    }
-
-    @Override
-    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
-        ctx.close();
-    }
-}

+ 0 - 20
src/main/java/cn/nosum/gateway/handler/FinalProcessHandler.java

@@ -1,20 +0,0 @@
-package cn.nosum.gateway.handler;
-
-import cn.nosum.common.dto.ResultInfo;
-import cn.nosum.common.http.entity.Context;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.SimpleChannelInboundHandler;
-
-public class FinalProcessHandler extends SimpleChannelInboundHandler<Context> {
-
-    @Override
-    protected void channelRead0(ChannelHandlerContext ctx, Context context) throws Exception {
-        // TODO 这里直接使用了 stat 脚本返回值作为输出,实际处理应该更为复杂
-        context.getResponse().write(ResultInfo.valueOf(context.getResult()));
-    }
-
-    @Override
-    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
-        ctx.close();
-    }
-}

+ 0 - 3
src/main/java/cn/nosum/gateway/handler/SlotProcessHandler.java

@@ -20,12 +20,9 @@ public class SlotProcessHandler extends SimpleChannelInboundHandler<Context> {
         ProcessorSlot<Context> chain = SlotChainProvider.newSlotChain();
         try {
             chain.exec(context);
-            // 传递上下文对象到下一个 handler
-            ctx.fireChannelRead(context);
         } catch (ExcludeException e) {
             context.getResponse().write(ResultInfo.valueOf(ResultEnum.URL_EXCLUDE));
         } catch (Throwable throwable) {
-            throwable.printStackTrace();
             context.getResponse().write(ResultInfo.valueOf(ResultEnum.FAILING));
         }
     }

+ 1 - 5
src/main/java/cn/nosum/gateway/handler/build/ContextHandlerBuilder.java

@@ -18,15 +18,11 @@ public class ContextHandlerBuilder implements HandlerBuilder{
             channelInitializer = new ChannelInitializer<SocketChannel>() {
                 // 客户端初始化处理
                 protected void initChannel(SocketChannel client) throws Exception {
-                    // Netty对HTTP协议的封装,顺序有要求
                     client.pipeline().addLast(new HttpRequestDecoder());
-                    client.pipeline().addLast(new HttpObjectAggregator(65535));//将多个消息转化成一个
+                    client.pipeline().addLast(new HttpObjectAggregator(65535));
                     client.pipeline().addLast(new HttpResponseEncoder());
                     client.pipeline().addLast(new FullHttpRequestHandler());
                     client.pipeline().addLast(new SlotProcessHandler());
-                    // TODO 根据激活扩展点优化
-                    client.pipeline().addLast(new FileProcessHandler());
-                    client.pipeline().addLast(new FinalProcessHandler());
                 }
             };
         }

+ 5 - 0
src/main/java/cn/nosum/gateway/slot/build/LinkSlotChainBuilder.java

@@ -3,15 +3,20 @@ package cn.nosum.gateway.slot.build;
 import cn.nosum.common.annotation.Adaptive;
 import cn.nosum.common.extension.ExtensionLoader;
 import cn.nosum.gateway.slot.ProcessorSlotChain;
+import cn.nosum.gateway.slot.chain.FileProcessorSlotChain;
+import cn.nosum.gateway.slot.chain.FinalProcessorSlotChain;
 import cn.nosum.gateway.slot.chain.LogProcessorSlotChain;
 import cn.nosum.gateway.slot.chain.UrlProcessorSlotChain;
 
 @Adaptive
 public class LinkSlotChainBuilder implements SlotChainBuilder {
     private ProcessorSlotChain chain=ExtensionLoader.getExtensionLoader(ProcessorSlotChain.class).getAdaptiveExtension();
+
     {
          chain.addLast(new UrlProcessorSlotChain());
          chain.addLast(new LogProcessorSlotChain());
+         chain.addLast(new FileProcessorSlotChain());
+         chain.addLast(new FinalProcessorSlotChain());
     }
 
     @Override

+ 25 - 0
src/main/java/cn/nosum/gateway/slot/chain/FileProcessorSlotChain.java

@@ -0,0 +1,25 @@
+package cn.nosum.gateway.slot.chain;
+
+import cn.nosum.common.constant.CommonConstants;
+import cn.nosum.common.http.entity.Context;
+import cn.nosum.common.util.LinuxCmd;
+import cn.nosum.common.util.NettyFileUtil;
+import cn.nosum.common.util.PropertiesUtil;
+import cn.nosum.gateway.slot.AbstractLinkedProcessorSlot;
+import com.alibaba.fastjson.JSON;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class FileProcessorSlotChain extends AbstractLinkedProcessorSlot<Context> {
+
+    @Override
+    public void exec(Context context) throws Throwable {
+        NettyFileUtil.dataToFile(JSON.toJSONString(context.getRequest().getParameters()),
+                PropertiesUtil.getProperty(CommonConstants.REQUEST_FILE_SAVE_FOLDER_NAME) + context.getRequest().getUrl(),
+                false);
+        context.setResult(LinuxCmd.executeLinuxCmd("stat "
+                + PropertiesUtil.getProperty(CommonConstants.REQUEST_FILE_SAVE_FOLDER_NAME)
+                + context.getRequest().getUrl()));
+        fireExec(context);
+    }
+}

+ 14 - 0
src/main/java/cn/nosum/gateway/slot/chain/FinalProcessorSlotChain.java

@@ -0,0 +1,14 @@
+package cn.nosum.gateway.slot.chain;
+
+import cn.nosum.common.dto.ResultInfo;
+import cn.nosum.common.http.entity.Context;
+import cn.nosum.gateway.slot.AbstractLinkedProcessorSlot;
+
+public class FinalProcessorSlotChain extends AbstractLinkedProcessorSlot<Context> {
+
+    @Override
+    public void exec(Context context) throws Throwable {
+        // TODO 这里直接使用了 stat 脚本返回值作为输出,实际处理应该更为复杂
+        context.getResponse().write(ResultInfo.valueOf(context.getResult()));
+    }
+}