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());//响应到浏览器
网友评论