最近在用Netty作開發,須要提供一個http web server,供調用方調用。採用Netty自己提供的HttpServerCodec
handler進行Http協議的解析,可是須要本身提供路由。java
最開始是經過對Http method及uri 採用多層if else 嵌套判斷的方法路由到真正的controller類:git
String uri = request.uri(); HttpMethod method = request.method(); if (method == HttpMethod.POST) { if (uri.startsWith("/login")) { //url參數解析,調用controller的方法 } else if (uri.startsWith("/logout")) { //同上 } } else if (method == HttpMethod.GET) { if (uri.startsWith("/")) { } else if (uri.startsWith("/status")) { } }
在只需提供login
及logout
API時,代碼能夠完成功能,但是隨着API的數量愈來愈多,須要支持的方法及uri愈來愈多,else if
愈來愈多,代碼愈來愈複雜。github
在阿里開發手冊中也提到過:web
所以首先考慮採用狀態設計模式及策略設計模式重構。spring
首先咱們知道每一個http請求都是由method及uri來惟一標識的,所謂路由就是經過這個惟一標識定位到controller類的中的某個方法。設計模式
所以把HttpLabel做爲狀態mvc
@Data @AllArgsConstructor public class HttpLabel { private String uri; private HttpMethod method; }
狀態接口:app
public interface Route { /** * 路由 * * @param request * @return */ GeneralResponse call(FullHttpRequest request); }
爲每一個狀態添加狀態實現:ide
public void route() { //單例controller類 final DemoController demoController = DemoController.getInstance(); Map<HttpLabel, Route> map = new HashMap<>(); map.put(new HttpLabel("/login", HttpMethod.POST), demoController::login); map.put(new HttpLabel("/logout", HttpMethod.POST), demoController::login); }
接到請求,判斷狀態,調用不一樣接口:測試
public class ServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> { @Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) { String uri = request.uri(); GeneralResponse generalResponse; if (uri.contains("?")) { uri = uri.substring(0, uri.indexOf("?")); } Route route = map.get(new HttpLabel(uri, request.method())); if (route != null) { ResponseUtil.response(ctx, request, route.call(request)); } else { generalResponse = new GeneralResponse(HttpResponseStatus.BAD_REQUEST, "請檢查你的請求方法及url", null); ResponseUtil.response(ctx, request, generalResponse); } } }
使用狀態設計模式重構代碼,在增長url時只須要網map裏面put一個值就好了。
後來看了 JAVA反射+運行時註解實現URL路由 發現反射+註解的方式很優雅,代碼也不復雜。
下面介紹Netty使用反射實現URL路由。
路由註解:
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface RequestMapping { /** * 路由的uri * * @return */ String uri(); /** * 路由的方法 * * @return */ String method(); }
掃描classpath下帶有@RequestMapping
註解的方法,將這個方法放進一個路由Map:Map<HttpLabel, Action<GeneralResponse>> httpRouterAction
,key爲上面提到過的Http惟一標識 HttpLabel
,value爲經過反射調用的方法:
@Slf4j public class HttpRouter extends ClassLoader { private Map<HttpLabel, Action<GeneralResponse>> httpRouterAction = new HashMap<>(); private String classpath = this.getClass().getResource("").getPath(); private Map<String, Object> controllerBeans = new HashMap<>(); @Override protected Class<?> findClass(String name) throws ClassNotFoundException { String path = classpath + name.replaceAll("\\.", "/"); byte[] bytes; try (InputStream ins = new FileInputStream(path)) { try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { byte[] buffer = new byte[1024 * 5]; int b = 0; while ((b = ins.read(buffer)) != -1) { out.write(buffer, 0, b); } bytes = out.toByteArray(); } } catch (Exception e) { throw new ClassNotFoundException(); } return defineClass(name, bytes, 0, bytes.length); } public void addRouter(String controllerClass) { try { Class<?> cls = loadClass(controllerClass); Method[] methods = cls.getDeclaredMethods(); for (Method invokeMethod : methods) { Annotation[] annotations = invokeMethod.getAnnotations(); for (Annotation annotation : annotations) { if (annotation.annotationType() == RequestMapping.class) { RequestMapping requestMapping = (RequestMapping) annotation; String uri = requestMapping.uri(); String httpMethod = requestMapping.method().toUpperCase(); // 保存Bean單例 if (!controllerBeans.containsKey(cls.getName())) { controllerBeans.put(cls.getName(), cls.newInstance()); } Action action = new Action(controllerBeans.get(cls.getName()), invokeMethod); //若是須要FullHttpRequest,就注入FullHttpRequest對象 Class[] params = invokeMethod.getParameterTypes(); if (params.length == 1 && params[0] == FullHttpRequest.class) { action.setInjectionFullhttprequest(true); } // 保存映射關係 httpRouterAction.put(new HttpLabel(uri, new HttpMethod(httpMethod)), action); } } } } catch (Exception e) { log.warn("{}", e); } } public Action getRoute(HttpLabel httpLabel) { return httpRouterAction.get(httpLabel); } }
經過反射調用controller
類中的方法:
@Data @RequiredArgsConstructor @Slf4j public class Action<T> { @NonNull private Object object; @NonNull private Method method; private boolean injectionFullhttprequest; public T call(Object... args) { try { return (T) method.invoke(object, args); } catch (IllegalAccessException | InvocationTargetException e) { log.warn("{}", e); } return null; }
ServerHandler.java
處理以下:
//根據不一樣的請求API作不一樣的處理(路由分發) Action<GeneralResponse> action = httpRouter.getRoute(new HttpLabel(uri, request.method())); if (action != null) { if (action.isInjectionFullhttprequest()) { ResponseUtil.response(ctx, request, action.call(request)); } else { ResponseUtil.response(ctx, request, action.call()); } } else { //錯誤處理 generalResponse = new GeneralResponse(HttpResponseStatus.BAD_REQUEST, "請檢查你的請求方法及url", null); ResponseUtil.response(ctx, request, generalResponse); }
DemoController
方法配置:
@RequestMapping(uri = "/login", method = "POST") public GeneralResponse login(FullHttpRequest request) { User user = JsonUtil.fromJson(request, User.class); log.info("/login called,user: {}", user); return new GeneralResponse(null); }
測試結果以下:
完整代碼在 https://github.com/morethink/Netty-Route