netty(十二)http server url 与 处理方法映射(反射与注解)spring环境
使用反射与注解
类级别注解使用spring的
方法级别注解自定义
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented public @interface ServiceRequestMapping { String value() default ""; }
public class PathAlreadyExistException extends RuntimeException { public PathAlreadyExistException(String message) { super(message); } }
public class RequestController { private static final Logger logger = LoggerFactory.getLogger(RequestController.class); private static final Map<String, Route> DISPATCH_MAP = new ConcurrentHashMap<>(); private RequestController() {} /** * 启动时集成绑定 */ public static void initMap() { Map<String, Object> map = ApplicationHelper.getBeansWithAnnotation(Repository.class); for (Map.Entry<String, Object> entry : map.entrySet()) { Object bean = entry.getValue(); Class<?> clazz = bean.getClass(); Method[] methods = clazz.getMethods(); for (Method method : methods) { ServiceRequestMapping an = method.getAnnotation(ServiceRequestMapping.class); if (null != an) { String anName = an.value(); Object old = DISPATCH_MAP.putIfAbsent(anName, Route.buildRoute(method, bean)); if(old != null) { throw new PathAlreadyExistException(anName + " already exist!"); } logger.info("req map - {} - {}", anName, bean); } } } } /** * 运行时反射调用 * @param path * @param paras * @return */ public static Object callMap(String path, Object... paras) { Route route = DISPATCH_MAP.get(path); if(route != null) { try { return route.method.invoke(route.newInstance, paras); } catch (Exception e) { logger.error(ExceptionUtils.getStackTrace(e)); return null; } } else { logger.error("the path has no method"); return null; } } /** * 实体 */ private static class Route { private Method method; private Object newInstance; private Route(){} public static Route buildRoute(Method method, Object newInstance) { Route route = new Route(); route.method = method; route.newInstance = newInstance; return route; } } }
调用
@ServiceRequestMapping("list") public List query(JSONObject para) { StringBuilder stringBuilder = new StringBuilder(100).append("select * from ib_origin where 1 ");
@Override protected void channelRead0(ChannelHandlerContext ctx, JSONObject msg) throws Exception { LOGGER.debug("收到客户端http请求:{}", msg); String flag = (String)msg.get("flag"); ResponseMessage message = null; TokenService tokenService = (TokenService)ApplicationHelper.getBean(TokenService.class); if(flag == null || "".equals(flag)) { message = ResponseMessage.genFail().setMessage("url 非法"); } else if("login".equals(flag)) { message = tokenService.checkAuth(msg); } else { // 先验证token boolean hasAuth = tokenService.checkToken(msg); if(hasAuth) { Object res = RequestController.callMap(flag, msg); if(res != null) { message = ResponseMessage.genSuccess().setResult(res); } else { message = ResponseMessage.genFail().setMessage("服务器繁忙"); } } else { message = ResponseMessage.genFail().setMessage("token 非法"); } } ChannelFuture channelFuture = ctx.writeAndFlush(message); // channelFuture.addListener(ChannelFutureListener.CLOSE); channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if(!future.isSuccess()) { LOGGER.error(ExceptionUtils.getStackTrace(future.cause())); future.channel().close(); } } }); }