隨著公司的規模及項目的增多,會有一種透明傳輸的需求,而透明傳輸的這一層就用來做權限控制,灰度發布,流量統計。
實現透傳需要注意的幾點:
1.Spring MVC實現url通配,後端服務的url各式各樣,並不能按照你所設想的長度,so,通配符能解決這個問題。
@RequestMapping(value = "/{serviceName}/{methodName}/**/", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"}) public @ResponseBody Object getHttp(@PathVariable(value = "serviceName") String serviceName, @PathVariable(value = "methodName") String methodName, HttpServletRequest request, HttpServletResponse response) throws ServiceException { try { return sendGetHttp(serviceName, methodName, request, response); } catch (ServiceException e) { LOGGER.error("getHttp_service", e); response.setStatus(520); return ResponseEntity.fail(e.getErrorCode(), e.getErrorMessage()); } catch (SystemException e) { LOGGER.error("getHttp_system", e); response.setStatus(520); return ResponseEntity.error(e.getErrorMessage()); } catch (Exception e) { LOGGER.error("getHttp_exception", e); response.setStatus(520); return ResponseEntity.error(e.getMessage()); } }
2.body流解析,POST/PUT/PATCH,一般都是包含body的請求,但是作為透明傳輸層,就是有那麼一個不包含body,所以透明傳輸的請求不適合加上@RequestBody,這時body的信息,我們可以通過HttpServletRequest解析出來。
// request中解析出body private String resolveRequestToBody(HttpServletRequest request) throws IOException { int length = request.getContentLength(); String requestStr = null; if (length != 0) { InputStream inputStream = request.getInputStream(); byte b[] = new byte[length]; inputStream.read(b); inputStream.close(); requestStr = new String(b); LOGGER.info("requestLength:" + length + ",requestType:" + request.getContentType() + ",body:" + requestStr); } return requestStr; }
附:
通配符詳解推薦一篇博客:http://www.codeweblog.com/springmvc%E7%AC%94%E8%AE%B0%E7%B3%BB%E5%88%97-5-requestmapping%E8%AF%B7%E6%B1%82value%E7%9A%84%E9%80%9A%E9%85%8D%E7%AC%A6%E8%AF%A6%E8%A7%A3/