├── NettyHttpServer.iml ├── src └── main │ ├── resources │ └── application.properties │ └── java │ └── com │ └── farsunset │ └── httpserver │ ├── netty │ ├── exception │ │ ├── IllegalPathDuplicatedException.java │ │ ├── IllegalPathNotFoundException.java │ │ └── IllegalMethodNotAllowedException.java │ ├── handler │ │ ├── IFunctionHandler.java │ │ ├── HelloWorldHandler.java │ │ ├── RequestBodyHandler.java │ │ └── PathVariableHandler.java │ ├── annotation │ │ └── NettyHttpHandler.java │ ├── iohandler │ │ ├── InterceptorHandler.java │ │ ├── FilterLogginglHandler.java │ │ └── HttpServerHandler.java │ ├── path │ │ └── Path.java │ └── http │ │ ├── NettyHttpResponse.java │ │ └── NettyHttpRequest.java │ ├── HttpServerApplication.java │ ├── dto │ └── Response.java │ └── configuration │ └── NettyHttpServer.java ├── target └── classes │ └── application.properties ├── .idea ├── encodings.xml ├── misc.xml ├── compiler.xml ├── uiDesigner.xml └── workspace.xml ├── .gitignore ├── pom.xml ├── README.md └── LICENSE /NettyHttpServer.iml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8080 2 | spring.application.name=netty-http-server 3 | -------------------------------------------------------------------------------- /target/classes/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8080 2 | spring.application.name=netty-http-server 3 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 17 | 18 | -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/netty/exception/IllegalPathDuplicatedException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013-2033 Xia Jun(3979434@qq.com). 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | *************************************************************************************** 17 | * * 18 | * Website : http://www.farsunset.com * 19 | * * 20 | *************************************************************************************** 21 | */ 22 | package com.farsunset.httpserver.netty.exception; 23 | 24 | public class IllegalPathDuplicatedException extends Exception { 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/netty/exception/IllegalPathNotFoundException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013-2033 Xia Jun(3979434@qq.com). 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | *************************************************************************************** 17 | * * 18 | * Website : http://www.farsunset.com * 19 | * * 20 | *************************************************************************************** 21 | */ 22 | package com.farsunset.httpserver.netty.exception; 23 | 24 | public class IllegalPathNotFoundException extends Exception { 25 | public IllegalPathNotFoundException() { 26 | super("PATH NOT FOUND"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/netty/exception/IllegalMethodNotAllowedException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013-2033 Xia Jun(3979434@qq.com). 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | *************************************************************************************** 17 | * * 18 | * Website : http://www.farsunset.com * 19 | * * 20 | *************************************************************************************** 21 | */ 22 | package com.farsunset.httpserver.netty.exception; 23 | 24 | public class IllegalMethodNotAllowedException extends Exception { 25 | public IllegalMethodNotAllowedException() { 26 | super("METHOD NOT ALLOWED"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/netty/handler/IFunctionHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013-2033 Xia Jun(3979434@qq.com). 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | *************************************************************************************** 17 | * * 18 | * Website : http://www.farsunset.com * 19 | * * 20 | *************************************************************************************** 21 | */ 22 | package com.farsunset.httpserver.netty.handler; 23 | 24 | 25 | import com.farsunset.httpserver.dto.Response; 26 | import com.farsunset.httpserver.netty.http.NettyHttpRequest; 27 | 28 | public interface IFunctionHandler { 29 | Response execute(NettyHttpRequest request); 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/netty/handler/HelloWorldHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013-2033 Xia Jun(3979434@qq.com). 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | *************************************************************************************** 17 | * * 18 | * Website : http://www.farsunset.com * 19 | * * 20 | *************************************************************************************** 21 | */ 22 | package com.farsunset.httpserver.netty.handler; 23 | 24 | 25 | import com.farsunset.httpserver.dto.Response; 26 | import com.farsunset.httpserver.netty.annotation.NettyHttpHandler; 27 | import com.farsunset.httpserver.netty.http.NettyHttpRequest; 28 | 29 | @NettyHttpHandler(path = "/hello/world") 30 | public class HelloWorldHandler implements IFunctionHandler { 31 | 32 | @Override 33 | public Response execute(NettyHttpRequest request) { 34 | return Response.ok("Hello World"); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/netty/annotation/NettyHttpHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013-2033 Xia Jun(3979434@qq.com). 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | *************************************************************************************** 17 | * * 18 | * Website : http://www.farsunset.com * 19 | * * 20 | *************************************************************************************** 21 | */ 22 | package com.farsunset.httpserver.netty.annotation; 23 | 24 | import java.lang.annotation.*; 25 | 26 | @Target({ElementType.TYPE}) 27 | @Retention(RetentionPolicy.RUNTIME) 28 | @Documented 29 | public @interface NettyHttpHandler { 30 | /** 31 | * 请求路径 32 | * @return 33 | */ 34 | String path() default ""; 35 | 36 | /** 37 | * 支持的提交方式 38 | * @return 39 | */ 40 | String method() default "GET"; 41 | 42 | /** 43 | * path和请求路径是否需要完全匹配。 如果是PathVariable传参数,设置为false 44 | * @return 45 | */ 46 | boolean equal() default true; 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/netty/handler/RequestBodyHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013-2033 Xia Jun(3979434@qq.com). 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | *************************************************************************************** 17 | * * 18 | * Website : http://www.farsunset.com * 19 | * * 20 | *************************************************************************************** 21 | */ 22 | package com.farsunset.httpserver.netty.handler; 23 | import com.farsunset.httpserver.dto.Response; 24 | import com.farsunset.httpserver.netty.annotation.NettyHttpHandler; 25 | import com.farsunset.httpserver.netty.http.NettyHttpRequest; 26 | 27 | 28 | @NettyHttpHandler(path = "/request/body",method = "POST") 29 | public class RequestBodyHandler implements IFunctionHandler { 30 | @Override 31 | public Response execute(NettyHttpRequest request) { 32 | /** 33 | * 可以在此拿到json转成业务需要的对象 34 | */ 35 | String json = request.contentText(); 36 | return Response.ok(json); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/HttpServerApplication.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013-2033 Xia Jun(3979434@qq.com). 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | *************************************************************************************** 17 | * * 18 | * Website : http://www.farsunset.com * 19 | * * 20 | *************************************************************************************** 21 | */ 22 | package com.farsunset.httpserver; 23 | 24 | import com.farsunset.httpserver.netty.annotation.NettyHttpHandler; 25 | import org.springframework.boot.WebApplicationType; 26 | import org.springframework.boot.autoconfigure.SpringBootApplication; 27 | import org.springframework.boot.builder.SpringApplicationBuilder; 28 | import org.springframework.context.annotation.ComponentScan; 29 | 30 | @SpringBootApplication() 31 | @ComponentScan(includeFilters = @ComponentScan.Filter(NettyHttpHandler.class)) 32 | 33 | public class HttpServerApplication { 34 | 35 | public static void main(String[] args) { 36 | new SpringApplicationBuilder(HttpServerApplication.class).web(WebApplicationType.NONE).run(args); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.farsunset 8 | netty.http.server 9 | 1.0-SNAPSHOT 10 | 11 | 12 | org.springframework.boot 13 | spring-boot-starter-parent 14 | 2.1.1.RELEASE 15 | 16 | 17 | 18 | 19 | 4.1.32.Final 20 | 2.8.5 21 | 22 | 23 | 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter 28 | 29 | 30 | com.google.code.gson 31 | gson 32 | ${gson.version} 33 | 34 | 35 | 36 | io.netty 37 | netty-handler 38 | ${netty.version} 39 | 40 | 41 | 42 | io.netty 43 | netty-codec-http 44 | ${netty.version} 45 | 46 | 47 | 48 | netty-http-server 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-maven-plugin 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/netty/handler/PathVariableHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013-2033 Xia Jun(3979434@qq.com). 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | *************************************************************************************** 17 | * * 18 | * Website : http://www.farsunset.com * 19 | * * 20 | *************************************************************************************** 21 | */ 22 | package com.farsunset.httpserver.netty.handler; 23 | 24 | import com.farsunset.httpserver.dto.Response; 25 | import com.farsunset.httpserver.netty.annotation.NettyHttpHandler; 26 | import com.farsunset.httpserver.netty.http.NettyHttpRequest; 27 | 28 | import java.util.HashMap; 29 | import java.util.LinkedList; 30 | import java.util.List; 31 | import java.util.Map; 32 | 33 | 34 | @NettyHttpHandler(path = "/moment/list/",equal = false) 35 | public class PathVariableHandler implements IFunctionHandler>> { 36 | @Override 37 | public Response>> execute(NettyHttpRequest request) { 38 | 39 | /** 40 | * 通过请求uri获取到path参数 41 | */ 42 | String id = request.getStringPathValue(3); 43 | 44 | List> list = new LinkedList<>(); 45 | HashMap data = new HashMap<>(); 46 | data.put("id","1"); 47 | data.put("name","Bluesky"); 48 | data.put("text","hello sea!"); 49 | data.put("time","2018-08-08 08:08:08"); 50 | list.add(data); 51 | return Response.ok(list); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/netty/iohandler/InterceptorHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013-2033 Xia Jun(3979434@qq.com). 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | *************************************************************************************** 17 | * * 18 | * Website : http://www.farsunset.com * 19 | * * 20 | *************************************************************************************** 21 | */ 22 | package com.farsunset.httpserver.netty.iohandler; 23 | 24 | import com.farsunset.httpserver.netty.http.NettyHttpResponse; 25 | import io.netty.channel.ChannelFutureListener; 26 | import io.netty.channel.ChannelHandler; 27 | import io.netty.channel.ChannelHandlerContext; 28 | import io.netty.channel.ChannelInboundHandlerAdapter; 29 | import io.netty.handler.codec.http.FullHttpRequest; 30 | import io.netty.handler.codec.http.HttpResponseStatus; 31 | import io.netty.util.ReferenceCountUtil; 32 | import org.springframework.stereotype.Component; 33 | 34 | 35 | @ChannelHandler.Sharable 36 | @Component 37 | /** 38 | * 在这里可以做拦截器,验证一些请求的合法性 39 | */ 40 | public class InterceptorHandler extends ChannelInboundHandlerAdapter { 41 | @Override 42 | public void channelRead(ChannelHandlerContext context, Object msg) { 43 | if (isPassed((FullHttpRequest) msg)){ 44 | context.fireChannelRead(msg); 45 | return; 46 | } 47 | 48 | ReferenceCountUtil.release(msg); 49 | context.writeAndFlush(NettyHttpResponse.make(HttpResponseStatus.UNAUTHORIZED)).addListener(ChannelFutureListener.CLOSE); 50 | } 51 | 52 | /** 53 | * 修改实现来验证合法性 54 | * @param request 55 | * @return 56 | */ 57 | private boolean isPassed(FullHttpRequest request){ 58 | return true; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/dto/Response.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013-2033 Xia Jun(3979434@qq.com). 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | *************************************************************************************** 17 | * * 18 | * Website : http://www.farsunset.com * 19 | * * 20 | *************************************************************************************** 21 | */ 22 | package com.farsunset.httpserver.dto; 23 | 24 | import com.google.gson.GsonBuilder; 25 | 26 | public final class Response { 27 | private int code; 28 | private String message; 29 | private T data; 30 | 31 | 32 | public Response(int code, String message, T data) { 33 | this.code = code; 34 | this.message = message; 35 | this.data = data; 36 | } 37 | 38 | @Override 39 | public String toString() { 40 | return "Response{" + 41 | "code=" + code + 42 | ", message='" + message + '\'' + 43 | ", data=" + data + 44 | '}'; 45 | } 46 | 47 | public String toJSONString(){ 48 | return new GsonBuilder().create().toJson(this); 49 | } 50 | 51 | public int getCode() { 52 | return code; 53 | } 54 | 55 | public String getMessage() { 56 | return message; 57 | } 58 | 59 | public T getData() { 60 | return data; 61 | } 62 | 63 | public static Response ok(T data) { 64 | return new Response<>(200, "ok", data); 65 | } 66 | public static Response ok() { 67 | return new Response(200, "ok", null); 68 | } 69 | 70 | public static Response ok(String msg, T data) { 71 | return new Response<>(200, msg, data); 72 | } 73 | 74 | public static Response fail(String msg) { 75 | return new Response(500, msg, null); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/netty/path/Path.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013-2033 Xia Jun(3979434@qq.com). 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | *************************************************************************************** 17 | * * 18 | * Website : http://www.farsunset.com * 19 | * * 20 | *************************************************************************************** 21 | */ 22 | package com.farsunset.httpserver.netty.path; 23 | 24 | 25 | import com.farsunset.httpserver.netty.annotation.NettyHttpHandler; 26 | 27 | public class Path { 28 | private String method; 29 | private String uri; 30 | private boolean equal; 31 | 32 | public static Path make(NettyHttpHandler annotation){ 33 | return new Path(annotation); 34 | } 35 | public Path(NettyHttpHandler annotation){ 36 | method = annotation.method(); 37 | uri = annotation.path(); 38 | equal = annotation.equal(); 39 | } 40 | public String getMethod() { 41 | return method; 42 | } 43 | 44 | public void setMethod(String method) { 45 | this.method = method; 46 | } 47 | 48 | public String getUri() { 49 | return uri; 50 | } 51 | 52 | public void setUri(String uri) { 53 | this.uri = uri; 54 | } 55 | 56 | public boolean isEqual() { 57 | return equal; 58 | } 59 | 60 | public void setEqual(boolean equal) { 61 | this.equal = equal; 62 | } 63 | 64 | @Override 65 | public String toString(){ 66 | return method.toUpperCase() + " " + uri.toUpperCase(); 67 | } 68 | @Override 69 | public int hashCode(){ 70 | return ("HTTP " + method.toUpperCase() + " " + uri.toUpperCase()).hashCode(); 71 | } 72 | @Override 73 | public boolean equals(Object object){ 74 | if (object instanceof Path){ 75 | Path path = (Path) object; 76 | return method.equalsIgnoreCase(path.method) && uri.equalsIgnoreCase(path.uri); 77 | } 78 | return false; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/configuration/NettyHttpServer.java: -------------------------------------------------------------------------------- 1 | package com.farsunset.httpserver.configuration; 2 | 3 | import com.farsunset.httpserver.netty.iohandler.InterceptorHandler; 4 | import com.farsunset.httpserver.netty.iohandler.FilterLogginglHandler; 5 | import com.farsunset.httpserver.netty.iohandler.HttpServerHandler; 6 | import io.netty.bootstrap.ServerBootstrap; 7 | import io.netty.channel.ChannelFuture; 8 | import io.netty.channel.ChannelInitializer; 9 | import io.netty.channel.EventLoopGroup; 10 | import io.netty.channel.nio.NioEventLoopGroup; 11 | import io.netty.channel.socket.SocketChannel; 12 | import io.netty.channel.socket.nio.NioChannelOption; 13 | import io.netty.channel.socket.nio.NioServerSocketChannel; 14 | import io.netty.handler.codec.http.HttpObjectAggregator; 15 | import io.netty.handler.codec.http.HttpServerCodec; 16 | import org.slf4j.Logger; 17 | import org.slf4j.LoggerFactory; 18 | import org.springframework.beans.factory.annotation.Value; 19 | import org.springframework.boot.context.event.ApplicationStartedEvent; 20 | import org.springframework.context.ApplicationListener; 21 | import org.springframework.context.annotation.Configuration; 22 | import org.springframework.lang.NonNull; 23 | 24 | import javax.annotation.Resource; 25 | 26 | 27 | @Configuration 28 | public class NettyHttpServer implements ApplicationListener { 29 | 30 | private static final Logger LOGGER = LoggerFactory.getLogger(NettyHttpServer.class); 31 | 32 | @Value("${server.port}") 33 | private int port; 34 | 35 | @Resource 36 | private InterceptorHandler interceptorHandler; 37 | 38 | @Resource 39 | private HttpServerHandler httpServerHandler; 40 | 41 | @Override 42 | public void onApplicationEvent(@NonNull ApplicationStartedEvent event) { 43 | 44 | ServerBootstrap bootstrap = new ServerBootstrap(); 45 | EventLoopGroup bossGroup = new NioEventLoopGroup(); 46 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 47 | 48 | bootstrap.group(bossGroup, workerGroup); 49 | bootstrap.channel(NioServerSocketChannel.class); 50 | bootstrap.childOption(NioChannelOption.TCP_NODELAY, true); 51 | bootstrap.childOption(NioChannelOption.SO_REUSEADDR,true); 52 | bootstrap.childOption(NioChannelOption.SO_KEEPALIVE,false); 53 | bootstrap.childOption(NioChannelOption.SO_RCVBUF, 2048); 54 | bootstrap.childOption(NioChannelOption.SO_SNDBUF, 2048); 55 | bootstrap.childHandler(new ChannelInitializer() { 56 | @Override 57 | public void initChannel(SocketChannel ch) { 58 | ch.pipeline().addLast("codec", new HttpServerCodec()); 59 | ch.pipeline().addLast("aggregator", new HttpObjectAggregator(512 * 1024)); 60 | ch.pipeline().addLast("logging", new FilterLogginglHandler()); 61 | ch.pipeline().addLast("interceptor", interceptorHandler); 62 | ch.pipeline().addLast("bizHandler", httpServerHandler); 63 | } 64 | }) 65 | ; 66 | ChannelFuture channelFuture = bootstrap.bind(port).syncUninterruptibly().addListener(future -> { 67 | String logBanner = "\n\n" + 68 | "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" + 69 | "* *\n" + 70 | "* *\n" + 71 | "* Netty Http Server started on port {}. *\n" + 72 | "* *\n" + 73 | "* *\n" + 74 | "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n"; 75 | LOGGER.info(logBanner, port); 76 | }); 77 | channelFuture.channel().closeFuture().addListener(future -> { 78 | LOGGER.info("Netty Http Server Start Shutdown ............"); 79 | bossGroup.shutdownGracefully(); 80 | workerGroup.shutdownGracefully(); 81 | }); 82 | } 83 | 84 | } -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/netty/iohandler/FilterLogginglHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013-2033 Xia Jun(3979434@qq.com). 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | *************************************************************************************** 17 | * * 18 | * Website : http://www.farsunset.com * 19 | * * 20 | *************************************************************************************** 21 | */ 22 | package com.farsunset.httpserver.netty.iohandler; 23 | 24 | import io.netty.channel.ChannelHandlerContext; 25 | import io.netty.channel.ChannelPromise; 26 | import io.netty.handler.codec.http.HttpRequest; 27 | import io.netty.handler.logging.LogLevel; 28 | import io.netty.handler.logging.LoggingHandler; 29 | 30 | import java.net.SocketAddress; 31 | 32 | import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH; 33 | import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE; 34 | 35 | public class FilterLogginglHandler extends LoggingHandler { 36 | public FilterLogginglHandler() { 37 | super(LogLevel.INFO); 38 | } 39 | 40 | public void channelRegistered(ChannelHandlerContext ctx) { 41 | ctx.fireChannelRegistered(); 42 | } 43 | 44 | public void channelUnregistered(ChannelHandlerContext ctx) { 45 | ctx.fireChannelUnregistered(); 46 | } 47 | 48 | public void channelActive(ChannelHandlerContext ctx) { 49 | ctx.fireChannelActive(); 50 | } 51 | 52 | public void channelInactive(ChannelHandlerContext ctx) { 53 | ctx.fireChannelInactive(); 54 | } 55 | 56 | public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { 57 | ctx.fireUserEventTriggered(evt); 58 | } 59 | 60 | public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise){ 61 | if (this.logger.isEnabled(this.internalLevel)) { 62 | this.logger.log(this.internalLevel,ctx.channel().toString() + " WRITE \n" + msg.toString()); 63 | } 64 | 65 | ctx.write(msg, promise); 66 | } 67 | 68 | public void channelRead(ChannelHandlerContext ctx, Object msg) { 69 | if (this.logger.isEnabled(this.internalLevel)) { 70 | HttpRequest request = (HttpRequest) msg; 71 | String log = request.method() + " " + request.uri() + " " + request.protocolVersion() + "\n" + 72 | CONTENT_TYPE + ": " + request.headers().get(CONTENT_TYPE) + "\n" + 73 | CONTENT_LENGTH + ": " + request.headers().get(CONTENT_LENGTH) + "\n"; 74 | this.logger.log(this.internalLevel,ctx.channel().toString() + " READ \n" + log); 75 | } 76 | ctx.fireChannelRead(msg); 77 | } 78 | 79 | 80 | 81 | 82 | public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) { 83 | ctx.bind(localAddress, promise); 84 | } 85 | 86 | public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { 87 | ctx.connect(remoteAddress, localAddress, promise); 88 | } 89 | 90 | public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) { 91 | ctx.disconnect(promise); 92 | } 93 | 94 | public void close(ChannelHandlerContext ctx, ChannelPromise promise) { 95 | ctx.close(promise); 96 | } 97 | 98 | public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) { 99 | ctx.deregister(promise); 100 | } 101 | 102 | public void channelReadComplete(ChannelHandlerContext ctx) { 103 | ctx.fireChannelReadComplete(); 104 | } 105 | 106 | public void channelWritabilityChanged(ChannelHandlerContext ctx) { 107 | ctx.fireChannelWritabilityChanged(); 108 | } 109 | 110 | public void flush(ChannelHandlerContext ctx) { 111 | ctx.flush(); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/netty/http/NettyHttpResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013-2033 Xia Jun(3979434@qq.com). 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | *************************************************************************************** 17 | * * 18 | * Website : http://www.farsunset.com * 19 | * * 20 | *************************************************************************************** 21 | */ 22 | package com.farsunset.httpserver.netty.http; 23 | 24 | import io.netty.buffer.ByteBuf; 25 | import io.netty.buffer.PooledByteBufAllocator; 26 | import io.netty.handler.codec.http.DefaultFullHttpResponse; 27 | import io.netty.handler.codec.http.FullHttpResponse; 28 | import io.netty.handler.codec.http.HttpResponseStatus; 29 | import io.netty.handler.codec.http.HttpVersion; 30 | 31 | import static io.netty.handler.codec.http.HttpHeaderNames.*; 32 | 33 | public class NettyHttpResponse extends DefaultFullHttpResponse { 34 | 35 | private static final PooledByteBufAllocator BYTE_BUF_ALLOCATOR = new PooledByteBufAllocator(false); 36 | 37 | private static final String CONTENT_NORMAL_200 = "{\"code\":200,\"message\":\"OK\"}"; 38 | private static final String CONTENT_ERROR_401 = "{\"code\":401,\"message\":\"UNAUTHORIZED\"}"; 39 | private static final String CONTENT_ERROR_404 = "{\"code\":404,\"message\":\"REQUEST PATH NOT FOUND\"}"; 40 | private static final String CONTENT_ERROR_405 = "{\"code\":405,\"message\":\"METHOD NOT ALLOWED\"}"; 41 | private static final String CONTENT_ERROR_500 = "{\"code\":500,\"message\":\"%s\"}"; 42 | 43 | private String content; 44 | 45 | private NettyHttpResponse(HttpResponseStatus status, ByteBuf buffer ) { 46 | super(HttpVersion.HTTP_1_1, status,buffer); 47 | headers().set(CONTENT_TYPE, "application/json"); 48 | headers().setInt(CONTENT_LENGTH, content().readableBytes()); 49 | 50 | /** 51 | * 支持CORS 跨域访问 52 | */ 53 | headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); 54 | headers().set(ACCESS_CONTROL_ALLOW_HEADERS, "Origin, X-Requested-With, Content-Type, Accept, RCS-ACCESS-TOKEN"); 55 | headers().set(ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE"); 56 | } 57 | 58 | public static FullHttpResponse make(HttpResponseStatus status) { 59 | if (HttpResponseStatus.UNAUTHORIZED == status) { 60 | return NettyHttpResponse.make(HttpResponseStatus.UNAUTHORIZED, CONTENT_ERROR_401); 61 | } 62 | if (HttpResponseStatus.NOT_FOUND == status) { 63 | return NettyHttpResponse.make(HttpResponseStatus.NOT_FOUND, CONTENT_ERROR_404); 64 | } 65 | if (HttpResponseStatus.METHOD_NOT_ALLOWED == status) { 66 | return NettyHttpResponse.make(HttpResponseStatus.METHOD_NOT_ALLOWED, CONTENT_ERROR_405); 67 | } 68 | return NettyHttpResponse.make(HttpResponseStatus.OK,CONTENT_NORMAL_200); 69 | } 70 | 71 | public static FullHttpResponse makeError(Exception exception) { 72 | String message = exception.getClass().getName() + ":" + exception.getMessage(); 73 | return NettyHttpResponse.make(HttpResponseStatus.INTERNAL_SERVER_ERROR, String.format(CONTENT_ERROR_500,message)); 74 | } 75 | 76 | public static FullHttpResponse ok(String content) { 77 | return make(HttpResponseStatus.OK,content); 78 | } 79 | 80 | private static FullHttpResponse make(HttpResponseStatus status,String content) { 81 | byte[] body = content.getBytes(); 82 | ByteBuf buffer = BYTE_BUF_ALLOCATOR.buffer(body.length); 83 | buffer.writeBytes(body); 84 | NettyHttpResponse response = new NettyHttpResponse(status,buffer); 85 | response.content = content; 86 | return response; 87 | } 88 | 89 | @Override 90 | public String toString(){ 91 | StringBuilder builder = new StringBuilder(); 92 | builder.append(protocolVersion().toString()).append(" ").append(status().toString()).append("\n"); 93 | builder.append(CONTENT_TYPE).append(": ").append(headers().get(CONTENT_TYPE)).append("\n"); 94 | builder.append(CONTENT_LENGTH).append(": ").append(headers().get(CONTENT_LENGTH)).append("\n"); 95 | builder.append("content-body").append(": ").append(content).append("\n"); 96 | return builder.toString(); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #### 使用介绍 2 | 参见简书图文教程 3 | ## [https://www.jianshu.com/p/89403b1b314d](https://www.jianshu.com/p/89403b1b314d) 4 | 5 | ### 1启动 NettyServer 6 | ``` 7 | @Configuration 8 | public class NettyHttpServer implements ApplicationListener { 9 | 10 | private static final Logger LOGGER = LoggerFactory.getLogger(NettyHttpServer.class); 11 | 12 | @Value("${server.port}") 13 | private int port; 14 | 15 | @Resource 16 | private InterceptorHandler interceptorHandler; 17 | 18 | @Resource 19 | private HttpServerHandler httpServerHandler; 20 | 21 | @Override 22 | public void onApplicationEvent(@NonNull ApplicationStartedEvent event) { 23 | 24 | ServerBootstrap bootstrap = new ServerBootstrap(); 25 | EventLoopGroup bossGroup = new NioEventLoopGroup(); 26 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 27 | 28 | bootstrap.group(bossGroup, workerGroup); 29 | bootstrap.channel(NioServerSocketChannel.class); 30 | bootstrap.childOption(NioChannelOption.TCP_NODELAY, true); 31 | bootstrap.childOption(NioChannelOption.SO_REUSEADDR,true); 32 | bootstrap.childOption(NioChannelOption.SO_KEEPALIVE,false); 33 | bootstrap.childOption(NioChannelOption.SO_RCVBUF, 2048); 34 | bootstrap.childOption(NioChannelOption.SO_SNDBUF, 2048); 35 | bootstrap.childHandler(new ChannelInitializer() { 36 | @Override 37 | public void initChannel(SocketChannel ch) { 38 | ch.pipeline().addLast("codec", new HttpServerCodec()); 39 | ch.pipeline().addLast("aggregator", new HttpObjectAggregator(512 * 1024)); 40 | ch.pipeline().addLast("logging", new FilterLogginglHandler()); 41 | ch.pipeline().addLast("interceptor", interceptorHandler); 42 | ch.pipeline().addLast("bizHandler", httpServerHandler); 43 | } 44 | }) 45 | ; 46 | ChannelFuture channelFuture = bootstrap.bind(port).syncUninterruptibly().addListener(future -> { 47 | String logBanner = "\n\n" + 48 | "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" + 49 | "* *\n" + 50 | "* *\n" + 51 | "* Netty Http Server started on port {}. *\n" + 52 | "* *\n" + 53 | "* *\n" + 54 | "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n"; 55 | LOGGER.info(logBanner, port); 56 | }); 57 | channelFuture.channel().closeFuture().addListener(future -> { 58 | LOGGER.info("Netty Http Server Start Shutdown ............"); 59 | bossGroup.shutdownGracefully(); 60 | workerGroup.shutdownGracefully(); 61 | }); 62 | } 63 | 64 | } 65 | ``` 66 | 67 | ### 2实现HttpHandler 也就是SpringMvc的Controller 68 | ``` 69 | @NettyHttpHandler(path = "/hello/world") 70 | public class HelloWorldHandler implements IFunctionHandler { 71 | 72 | @Override 73 | public Response execute(NettyHttpRequest request) { 74 | return Response.ok("Hello World"); 75 | } 76 | } 77 | 78 | 79 | ``` 80 | 81 | PathVariable 82 | 83 | ``` 84 | @NettyHttpHandler(path = "/moment/list/",equal = false) 85 | public class PathVariableHandler implements IFunctionHandler>> { 86 | @Override 87 | public Response>> execute(NettyHttpRequest request) { 88 | 89 | /** 90 | * 通过请求uri获取到path参数 91 | */ 92 | String id = request.getStringPathValue(3); 93 | 94 | List> list = new LinkedList<>(); 95 | HashMap data = new HashMap<>(); 96 | data.put("id","1"); 97 | data.put("name","Bluesky"); 98 | data.put("text","hello sea!"); 99 | data.put("time","2018-08-08 08:08:08"); 100 | list.add(data); 101 | return Response.ok(list); 102 | } 103 | } 104 | 105 | ``` 106 | 107 | RequestBody 108 | 109 | ``` 110 | @NettyHttpHandler(path = "/request/body",method = "POST") 111 | public class RequestBodyHandler implements IFunctionHandler { 112 | @Override 113 | public Response execute(NettyHttpRequest request) { 114 | /** 115 | * 可以在此拿到json转成业务需要的对象 116 | */ 117 | String json = request.contentText(); 118 | return Response.ok(json); 119 | } 120 | } 121 | 122 | ``` 123 | 124 | ### 3执行请求查看效果 125 | ![image.png](https://upload-images.jianshu.io/upload_images/2154278-752e5909766228df.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 126 | 127 | ![image.png](https://upload-images.jianshu.io/upload_images/2154278-4132dc17ef929834.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 128 | 129 | 130 | #### 优缺点 131 | ------------------------------------------------------------------------------------------- 132 | 优点 133 | 134 | 1 netty使用多路复用技术大幅提升性能 135 | 136 | 2 减少web容器依赖,减少jar包体积 137 | 138 | 3 灵活配置简单,适合所有需要提供restful接口的微服务应用 139 | 140 | 4 完全按照springmvc的模式开发配置 141 | 142 | 缺点 143 | 144 | 1 还没能做到和spirng DispatcherServlet那么强大到支持各种规则的path配置 145 | 146 | 2 获取各种参数还需要在controller里面通过HttpRequest来获取,没有springmvc自动注入参数方便 147 | 148 | 有问题欢迎随时提issues. Thanks 149 | 150 | -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/netty/http/NettyHttpRequest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013-2033 Xia Jun(3979434@qq.com). 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | *************************************************************************************** 17 | * * 18 | * Website : http://www.farsunset.com * 19 | * * 20 | *************************************************************************************** 21 | */ 22 | package com.farsunset.httpserver.netty.http; 23 | 24 | import io.netty.buffer.ByteBuf; 25 | import io.netty.handler.codec.DecoderResult; 26 | import io.netty.handler.codec.http.FullHttpRequest; 27 | import io.netty.handler.codec.http.HttpHeaders; 28 | import io.netty.handler.codec.http.HttpMethod; 29 | import io.netty.handler.codec.http.HttpVersion; 30 | 31 | import java.nio.charset.Charset; 32 | import java.util.Objects; 33 | 34 | public class NettyHttpRequest implements FullHttpRequest { 35 | 36 | private FullHttpRequest realRequest; 37 | 38 | public NettyHttpRequest(FullHttpRequest request){ 39 | this.realRequest = request; 40 | } 41 | 42 | public String contentText(){ 43 | return content().toString(Charset.forName("UTF-8")); 44 | } 45 | 46 | public long getLongPathValue(int index){ 47 | String[] paths = uri().split("/"); 48 | return Long.parseLong(paths[index]); 49 | } 50 | 51 | public String getStringPathValue(int index){ 52 | String[] paths = uri().split("/"); 53 | return paths[index]; 54 | } 55 | 56 | public int getIntPathValue(int index){ 57 | String[] paths = uri().split("/"); 58 | return Integer.parseInt(paths[index]); 59 | } 60 | 61 | public boolean isAllowed(String method){ 62 | return getMethod().name().equalsIgnoreCase(method); 63 | } 64 | 65 | public boolean matched(String path,boolean equal){ 66 | String uri = uri().toLowerCase(); 67 | return equal ? Objects.equals(path,uri) : uri.startsWith(path); 68 | } 69 | 70 | @Override 71 | public ByteBuf content() { 72 | return realRequest.content(); 73 | } 74 | 75 | @Override 76 | public HttpHeaders trailingHeaders() { 77 | return realRequest.trailingHeaders(); 78 | } 79 | 80 | @Override 81 | public FullHttpRequest copy() { 82 | return realRequest.copy(); 83 | } 84 | 85 | @Override 86 | public FullHttpRequest duplicate() { 87 | return realRequest.duplicate(); 88 | } 89 | 90 | @Override 91 | public FullHttpRequest retainedDuplicate() { 92 | return realRequest.retainedDuplicate(); 93 | } 94 | 95 | @Override 96 | public FullHttpRequest replace(ByteBuf byteBuf) { 97 | return realRequest.replace(byteBuf); 98 | } 99 | 100 | @Override 101 | public FullHttpRequest retain(int i) { 102 | return realRequest.retain(i); 103 | } 104 | 105 | @Override 106 | public int refCnt() { 107 | return realRequest.refCnt(); 108 | } 109 | 110 | @Override 111 | public FullHttpRequest retain() { 112 | return realRequest.retain(); 113 | } 114 | 115 | @Override 116 | public FullHttpRequest touch() { 117 | return realRequest.touch(); 118 | } 119 | 120 | @Override 121 | public FullHttpRequest touch(Object o) { 122 | return realRequest.touch(o); 123 | } 124 | 125 | @Override 126 | public boolean release() { 127 | return realRequest.release(); 128 | } 129 | 130 | @Override 131 | public boolean release(int i) { 132 | return realRequest.release(i); 133 | } 134 | 135 | @Override 136 | public HttpVersion getProtocolVersion() { 137 | return realRequest.protocolVersion(); 138 | } 139 | 140 | @Override 141 | public HttpVersion protocolVersion() { 142 | return realRequest.protocolVersion(); 143 | } 144 | 145 | @Override 146 | public FullHttpRequest setProtocolVersion(HttpVersion httpVersion) { 147 | return realRequest.setProtocolVersion(httpVersion); 148 | } 149 | 150 | @Override 151 | public HttpHeaders headers() { 152 | return realRequest.headers(); 153 | } 154 | 155 | @Override 156 | public HttpMethod getMethod() { 157 | return realRequest.getMethod(); 158 | } 159 | 160 | @Override 161 | public HttpMethod method() { 162 | return realRequest.method(); 163 | } 164 | 165 | @Override 166 | public FullHttpRequest setMethod(HttpMethod httpMethod) { 167 | return realRequest.setMethod(httpMethod); 168 | } 169 | 170 | @Override 171 | public String getUri() { 172 | return realRequest.getUri(); 173 | } 174 | 175 | @Override 176 | public String uri() { 177 | return realRequest.uri(); 178 | } 179 | 180 | @Override 181 | public FullHttpRequest setUri(String s) { 182 | return realRequest.setUri(s); 183 | } 184 | 185 | @Override 186 | public DecoderResult getDecoderResult() { 187 | return realRequest.getDecoderResult(); 188 | } 189 | 190 | @Override 191 | public DecoderResult decoderResult() { 192 | return realRequest.decoderResult(); 193 | } 194 | 195 | @Override 196 | public void setDecoderResult(DecoderResult decoderResult) { 197 | realRequest.setDecoderResult(decoderResult); 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /src/main/java/com/farsunset/httpserver/netty/iohandler/HttpServerHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013-2033 Xia Jun(3979434@qq.com). 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | *************************************************************************************** 17 | * * 18 | * Website : http://www.farsunset.com * 19 | * * 20 | *************************************************************************************** 21 | */ 22 | package com.farsunset.httpserver.netty.iohandler; 23 | 24 | 25 | import com.farsunset.httpserver.dto.Response; 26 | import com.farsunset.httpserver.netty.annotation.NettyHttpHandler; 27 | import com.farsunset.httpserver.netty.exception.IllegalMethodNotAllowedException; 28 | import com.farsunset.httpserver.netty.exception.IllegalPathDuplicatedException; 29 | import com.farsunset.httpserver.netty.exception.IllegalPathNotFoundException; 30 | import com.farsunset.httpserver.netty.handler.IFunctionHandler; 31 | import com.farsunset.httpserver.netty.http.NettyHttpRequest; 32 | import com.farsunset.httpserver.netty.http.NettyHttpResponse; 33 | import com.farsunset.httpserver.netty.path.Path; 34 | import io.netty.channel.ChannelFutureListener; 35 | import io.netty.channel.ChannelHandler; 36 | import io.netty.channel.ChannelHandlerContext; 37 | import io.netty.channel.SimpleChannelInboundHandler; 38 | import io.netty.handler.codec.http.FullHttpRequest; 39 | import io.netty.handler.codec.http.FullHttpResponse; 40 | import io.netty.handler.codec.http.HttpResponseStatus; 41 | import io.netty.util.ReferenceCountUtil; 42 | import org.slf4j.Logger; 43 | import org.slf4j.LoggerFactory; 44 | import org.springframework.context.ApplicationContext; 45 | import org.springframework.context.ApplicationContextAware; 46 | import org.springframework.stereotype.Component; 47 | 48 | import java.util.HashMap; 49 | import java.util.Map; 50 | import java.util.Optional; 51 | import java.util.concurrent.ExecutorService; 52 | import java.util.concurrent.Executors; 53 | import java.util.concurrent.atomic.AtomicBoolean; 54 | import java.util.function.Predicate; 55 | import java.util.stream.Stream; 56 | 57 | @ChannelHandler.Sharable 58 | @Component 59 | public class HttpServerHandler extends SimpleChannelInboundHandler implements ApplicationContextAware { 60 | 61 | private static final Logger LOGGER = LoggerFactory.getLogger(HttpServerHandler.class); 62 | 63 | private HashMap functionHandlerMap = new HashMap<>(); 64 | 65 | private ExecutorService executor = Executors.newCachedThreadPool(runnable -> { 66 | Thread thread = Executors.defaultThreadFactory().newThread(runnable); 67 | thread.setName("NettyHttpHandler-" + thread.getName()); 68 | return thread; 69 | }); 70 | 71 | @Override 72 | public void channelReadComplete(ChannelHandlerContext ctx) { 73 | ctx.flush(); 74 | } 75 | 76 | @Override 77 | protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) { 78 | FullHttpRequest copyRequest = request.copy(); 79 | executor.execute(() -> onReceivedRequest(ctx,new NettyHttpRequest(copyRequest))); 80 | } 81 | 82 | 83 | private void onReceivedRequest(ChannelHandlerContext context, NettyHttpRequest request){ 84 | FullHttpResponse response = handleHttpRequest(request); 85 | context.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); 86 | ReferenceCountUtil.release(request); 87 | } 88 | 89 | private FullHttpResponse handleHttpRequest(NettyHttpRequest request) { 90 | 91 | IFunctionHandler functionHandler = null; 92 | 93 | try { 94 | functionHandler = matchFunctionHandler(request); 95 | Response response = functionHandler.execute(request); 96 | return NettyHttpResponse.ok(response.toJSONString()); 97 | } 98 | catch (IllegalMethodNotAllowedException error){ 99 | return NettyHttpResponse.make(HttpResponseStatus.METHOD_NOT_ALLOWED); 100 | } 101 | catch (IllegalPathNotFoundException error){ 102 | return NettyHttpResponse.make(HttpResponseStatus.NOT_FOUND); 103 | } 104 | catch (Exception error){ 105 | LOGGER.error(functionHandler.getClass().getSimpleName() + " Error",error); 106 | return NettyHttpResponse.makeError(error); 107 | } 108 | } 109 | 110 | @Override 111 | public void setApplicationContext(ApplicationContext applicationContext) { 112 | Map handlers = applicationContext.getBeansWithAnnotation(NettyHttpHandler.class); 113 | for (Map.Entry entry : handlers.entrySet()) { 114 | Object handler = entry.getValue(); 115 | Path path = Path.make(handler.getClass().getAnnotation(NettyHttpHandler.class)); 116 | if (functionHandlerMap.containsKey(path)){ 117 | LOGGER.error("IFunctionHandler has duplicated :" + path.toString(),new IllegalPathDuplicatedException()); 118 | System.exit(0); 119 | } 120 | functionHandlerMap.put(path, (IFunctionHandler) handler); 121 | } 122 | } 123 | 124 | private IFunctionHandler matchFunctionHandler(NettyHttpRequest request) throws IllegalPathNotFoundException, IllegalMethodNotAllowedException { 125 | 126 | AtomicBoolean matched = new AtomicBoolean(false); 127 | 128 | Stream stream = functionHandlerMap.keySet().stream() 129 | .filter(((Predicate) path -> { 130 | /** 131 | *过滤 Path URI 不匹配的 132 | */ 133 | if (request.matched(path.getUri(), path.isEqual())) { 134 | matched.set(true); 135 | return matched.get(); 136 | } 137 | return false; 138 | 139 | }).and(path -> { 140 | /** 141 | * 过滤 Method 匹配的 142 | */ 143 | return request.isAllowed(path.getMethod()); 144 | })); 145 | 146 | Optional optional = stream.findFirst(); 147 | 148 | stream.close(); 149 | 150 | if (!optional.isPresent() && !matched.get()){ 151 | throw new IllegalPathNotFoundException(); 152 | } 153 | 154 | if (!optional.isPresent() && matched.get()){ 155 | throw new IllegalMethodNotAllowedException(); 156 | } 157 | 158 | return functionHandlerMap.get(optional.get()); 159 | } 160 | 161 | } 162 | -------------------------------------------------------------------------------- /.idea/uiDesigner.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /.idea/workspace.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | false 142 | 143 | 144 | 171 | 172 | 173 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 |