/** * 微服务之间传递的唯一标识 */ public static final String X_REQUEST_ID = "X-Request-Id"; @Override public void apply(RequestTemplate template) { HttpServletRequest httpServletRequest = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .getRequest(); if (httpServletRequest != null) { Map<String, String> headers = getHeaders(httpServletRequest); // 传递所有请求头,防止部分丢失 for (Map.Entry<String, String> entry : headers.entrySet()) { // 防止添加重复 if (!template.headers().containsKey(entry.getKey())) { template.header(entry.getKey(), entry.getValue()); } } // 微服务之间传递的唯一标识,区分大小写所以通过httpServletRequest查询 if (headers.containsKey(X_REQUEST_ID)) { String traceId = headers.get(X_REQUEST_ID); //不做处理 // MDC.put("traceId", traceId); log.info("FeignRequestInterceptor X-Request-Id:{}", traceId); } if (log.isDebugEnabled()) { log.debug("FeignRequestInterceptor:{}", template.toString()); } } }
private Map<String, String> getHeaders(HttpServletRequest request) { Map<String, String> map = new LinkedHashMap<>(); Enumeration<String> enumeration = request.getHeaderNames(); if (enumeration != null) { while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); String value = request.getHeader(key); map.put(key, value); } } return map; }