美文网首页
ThreadLocal相关

ThreadLocal相关

作者: BySjm | 来源:发表于2020-01-08 23:01 被阅读0次
    • 代码示例Entity
    public class UserHolder {
    
        private static ThreadLocal<String> threadLocal = new ThreadLocal<>();
    
        public static String getUserId() {
            return threadLocal.get();
        }
    
        public static void setUserId(String userId) {
            threadLocal.set(userId);
        }
    
        public static void removeUserId() {
            threadLocal.remove();
        }
    
    }
    
    • 代码示例 拦截器
    /**
     * 拦截器
     * 拦截进入到购物车微服务的所有请求,把userId放入到UserHolder里
     */
    public class UserInterceptor implements HandlerInterceptor {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            String userId = request.getHeader("USER_ID");
            UserHolder.setUserId(userId);
            return true;
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            UserHolder.removeUserId();
        }
    }
    
    • 代码示例 配置类
    @Configuration
    public class MvcConfig implements WebMvcConfigurer {
    
        /**
         * 添加拦截器的方法
         * @param registry
         */
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
    
            registry.addInterceptor(new UserInterceptor()).addPathPatterns("/**");
        }
    }
    

    • 网关获取Cookie,解析Token,获取Payload,得到UserInfo对象。把UserInfo中的userId放入到头信息中
    ctx.addZuulRequestHeader("USER_ID",userInfo.getId().toString());//请求微服务的
    //ctx.addZuulResponseHeader("USER_ID",userInfo.getId().toString());//响应到浏览器
    

    相关文章

      网友评论

          本文标题:ThreadLocal相关

          本文链接:https://www.haomeiwen.com/subject/oojeactx.html