Browse Source

青涩知夏->创建了项目

青涩知夏 4 years ago
commit
b13ffdb525

+ 31 - 0
pom.xml

@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>cn.nosum</groupId>
+    <artifactId>nosum-gateway</artifactId>
+    <version>1.0-SNAPSHOT</version>
+
+
+    <properties>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+        <maven.compiler.source>1.8</maven.compiler.source>
+        <maven.compiler.target>1.8</maven.compiler.target>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>io.netty</groupId>
+            <artifactId>netty-all</artifactId>
+            <version>4.1.20.Final</version>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+            <version>1.2.4</version>
+        </dependency>
+    </dependencies>
+
+</project>

+ 9 - 0
src/main/java/cn/nosum/NoSumGateWayStart.java

@@ -0,0 +1,9 @@
+package cn.nosum;
+
+import cn.nosum.container.NettyGatewayContainer;
+
+public class NoSumGateWayStart {
+    public static void main(String[] args) {
+        new NettyGatewayContainer().start();
+    }
+}

+ 57 - 0
src/main/java/cn/nosum/container/NettyGatewayContainer.java

@@ -0,0 +1,57 @@
+package cn.nosum.container;
+
+import cn.nosum.handler.GateWayHandler;
+import cn.nosum.handler.HttpRequestHandler;
+import io.netty.bootstrap.ServerBootstrap;
+import io.netty.channel.*;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioServerSocketChannel;
+import io.netty.handler.codec.http.HttpRequestDecoder;
+import io.netty.handler.codec.http.HttpResponseEncoder;
+
+
+//Netty就是一个同时支持多协议的网络通信框架
+public class NettyGatewayContainer {
+	private int port = 8888;
+	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(new ChannelInitializer<SocketChannel>() {
+						// 客户端初始化处理
+						protected void initChannel(SocketChannel client) throws Exception {
+							// Netty对HTTP协议的封装,顺序有要求
+							// HttpResponseEncoder 编码器
+							client.pipeline().addLast(new HttpResponseEncoder());
+							// HttpRequestDecoder 解码器
+							client.pipeline().addLast(new HttpRequestDecoder());
+							// 业务逻辑处理
+							client.pipeline().addLast(new HttpRequestHandler());
+							client.pipeline().addLast(new GateWayHandler());
+						}
+					})
+					// 针对主线程的配置 分配线程最大数量 128
+					.option(ChannelOption.SO_BACKLOG, 128)
+					// 针对子线程的配置 保持长连接
+					.childOption(ChannelOption.SO_KEEPALIVE, true);
+
+			// 启动服务器
+			ChannelFuture f = server.bind(port).sync();
+			System.out.println("已启动,监听的端口是:" + port);
+			f.channel().closeFuture().sync();
+		}catch (Exception e){
+			e.printStackTrace();
+		}finally {
+			// 关闭线程池
+			bossGroup.shutdownGracefully();
+			workerGroup.shutdownGracefully();
+		}
+	}
+}

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

@@ -0,0 +1,27 @@
+package cn.nosum.handler;
+
+import cn.nosum.http.Request;
+import cn.nosum.http.Response;
+import com.alibaba.fastjson.JSONObject;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+
+public  class GateWayHandler extends ChannelInboundHandlerAdapter {
+		private String msg ="请求URL是:";
+		@Override
+		public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+			if (msg instanceof Request){
+				Request request = (Request) msg;
+				Response response = new Response(ctx,request.getReq());
+				// 实际业务处理
+				JSONObject obj = new JSONObject();
+				obj.put("msg",this.msg+request.getUrl());
+				response.write(obj);
+			}
+		}
+
+		@Override
+		public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+
+		}
+	}

+ 30 - 0
src/main/java/cn/nosum/handler/HttpRequestHandler.java

@@ -0,0 +1,30 @@
+package cn.nosum.handler;
+
+import cn.nosum.http.Request;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.handler.codec.http.HttpRequest;
+
+public class HttpRequestHandler extends ChannelInboundHandlerAdapter {
+    @Override
+    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+        if (msg instanceof HttpRequest){
+            HttpRequest req = (HttpRequest) msg;
+            // TODO
+            Request request = new Request(ctx,req);
+            String uri=request.getUrl();
+            if (uri.equals("/favicon.ico")) {
+                return;
+            }
+            System.err.println(request.getParameter("name"));
+            System.err.println(request.getUrl());
+            // 传递request对象到下一个handler
+            ctx.fireChannelRead(request);
+        }
+    }
+
+    @Override
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+
+    }
+}

+ 7 - 0
src/main/java/cn/nosum/handler/spi/IRequestHandler.java

@@ -0,0 +1,7 @@
+package cn.nosum.handler.spi;
+
+
+public interface IRequestHandler {
+    boolean doCheck(Object msg);
+    void doRun(Object msg);
+}

+ 48 - 0
src/main/java/cn/nosum/http/Request.java

@@ -0,0 +1,48 @@
+package cn.nosum.http;
+
+
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.http.HttpRequest;
+import io.netty.handler.codec.http.QueryStringDecoder;
+
+import java.util.List;
+import java.util.Map;
+
+public class Request {
+
+	private ChannelHandlerContext ctx;
+
+	private HttpRequest req;
+
+	public Request(ChannelHandlerContext ctx, HttpRequest req) {
+		this.ctx = ctx;
+		this.req = req;
+	}
+
+	public HttpRequest getReq() {
+		return req;
+	}
+
+	public String getUrl() {
+		return req.uri();
+	}
+
+	public String getMethod() {
+		return req.method().name();
+	}
+
+	public Map<String, List<String>> getParameters() {
+		QueryStringDecoder decoder = new QueryStringDecoder(req.uri());
+		return decoder.parameters();
+	}
+
+	public String getParameter(String name) {
+		Map<String, List<String>> params = getParameters();
+		List<String> param = params.get(name);
+		if (null == param) {
+			return null;
+		} else {
+			return param.get(0);
+		}
+	}
+}

+ 42 - 0
src/main/java/cn/nosum/http/Response.java

@@ -0,0 +1,42 @@
+package cn.nosum.http;
+
+import com.alibaba.fastjson.JSONObject;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.http.*;
+
+import java.nio.charset.StandardCharsets;
+
+
+public class Response {
+
+    // SocketChannel的封装
+    private ChannelHandlerContext ctx;
+
+    private HttpRequest req;
+
+    public Response(ChannelHandlerContext ctx, HttpRequest req) {
+        this.ctx = ctx;
+        this.req = req;
+    }
+
+    public void write(JSONObject out) throws Exception {
+        try {
+            if (out == null) {
+                return;
+            }
+            // 设置 http协议及请求头信息
+            FullHttpResponse response = new DefaultFullHttpResponse(
+                    // 设置http版本为1.1
+                    HttpVersion.HTTP_1_1,
+                    // 设置响应状态码
+                    HttpResponseStatus.OK,
+                    // 将输出值写出 编码为UTF-8
+                    Unpooled.wrappedBuffer(out.toJSONString().getBytes(StandardCharsets.UTF_8)));
+            response.headers().set("Content-Type", "application/json;");
+            ctx.writeAndFlush(response);
+        } finally {
+            ctx.close();
+        }
+    }
+}

+ 19 - 0
src/main/java/cn/nosum/http/Servlet.java

@@ -0,0 +1,19 @@
+package cn.nosum.http;
+
+public abstract class Servlet {
+	
+	public void service(Request request, Response response) throws Exception {
+		
+		//由service方法来决定,是调用doGet或者调用doPost
+		if("GET".equalsIgnoreCase(request.getMethod())){
+			doGet(request, response);
+		}else{
+			doPost(request, response);
+		}
+
+	}
+	
+	public abstract void doGet(Request request, Response response) throws Exception;
+	
+	public abstract void doPost(Request request, Response response) throws Exception;
+}

+ 1 - 0
src/main/resources/application.properties

@@ -0,0 +1 @@
+port=8888