实战SpringCloud通用请求字段拦截处理 (2)

这里添加一个简单的工具类,将HttpServletRequest通过getHeader方法,生成CommonHeader类:

public class HttpUtil { /** * 获取请求头信息 * * @param request * @return */ public static CommonHeader getCommonHeader(HttpServletRequest request) { String UID = request.getHeader("uid"); Long uid = null; if (StringUtils.isNotBlank(UID)) { uid = Long.parseLong(UID); } return new CommonHeader(HttpUtil.getIp(request), request.getHeader("deviceId"), uid); } /** * 获取IP * * @param request * @return */ public static String getIp(HttpServletRequest request) { String ip = request.getHeader("X-Forwarded-For"); if (null != ip && !"".equals(ip.trim()) && !"unknown".equalsIgnoreCase(ip)) { int index = ip.indexOf(','); if (index != -1) { return ip.substring(0, index); } else { return ip; } } ip = request.getHeader("X-Real-IP"); if (null != ip && !"".equals(ip.trim()) && !"unknown".equalsIgnoreCase(ip)) { return ip; } return request.getRemoteAddr(); } } 拦截器类实现

最核心的实现终于出场了,这里继承HandlerInterceptorAdapter,这里作了简化处理:

/** * 请求头处理 * * @author yangfei */ @Component public class BaseInterceptor extends HandlerInterceptorAdapter { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BaseInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { RequestWrap.getThreadLocal().set(HttpUtil.getCommonHeader(request)); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { RequestWrap.getThreadLocal().remove(); } @Override public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { } }

如上一章节描述的逻辑,在preHandle方法内将request中的ip,uid,deviceId封装到RequestWrap对象里,在afterCompletion中对该线程的ThreadLocal值进行释放。

业务接口方法的使用

在Controller类的接口方法中,如要获取uid信息,只需要调用RequestWrap.getUid()方法即可,再也不需要在每个接口上声明uid参数了,如下示例:

/** * 获取用户基础信息 */ @PostMapping(value = "/user/info") public Response<UserInfo> getUserInfo() { return userManager.getUserInfo(RequestWrap.getUid()); } 总结

这个实战的目标是解决通用header信息的在接口的重复定义问题,基于HandlerInterceptorAdapter拦截器的实现,ThreadLocal对线程访问数据的隔离来实现的,在实际生产项目应用中有很好的借鉴意义,希望对你有帮助。

专注Java高并发、分布式架构,更多技术干货分享与心得,请关注公众号:Java架构社区
可以扫左边二维码添加好友,邀请你加入Java架构社区微信群共同探讨技术

Java架构社区

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpxggw.html