1.FeginConfig 配置
@Configuration @Slf4j public class FeignConfig implements RequestInterceptor { @Override public void apply(RequestTemplate requestTemplate) { HttpServletRequest request = getServletRequest(); if (null == request) { return; } UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal(); if (user != null) { try { String userJson = JSON.toJSONString(user); requestTemplate.header("USER_INFO", new String[]{URLDecoder.decode(userJson, "UTF-8")}); } catch (UnsupportedEncodingException e) { log.error("用户信息设置错误", e); } } } private HttpServletRequest getServletRequest() { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); } }
2.fegin 调用配置,加上配置 configuration = {FeignConfig.class}
@FeignClient(name = "user-server", configuration = {FeignConfig.class}) public interface WebUserClient extends UserClient { }
3.然后服务方 拦截请求 获取 request.getHeader("USER_INFO") 用户信息
@Slf4j public class AuthorizationInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { String userJson = request.getHeader("USER_INFO"); if (StringUtils.isNotBlank(userJson)) { try { userJson = URLDecoder.decode(userJson, "UTF-8"); UserInfo userInfo = JSON.parseObject(userJson, UserInfo.class); //将UserInfo放入上下文中 UserContext.set(userInfo); } catch (UnsupportedEncodingException e) { log.error("init userInfo error", e); } } return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { //关闭threadLocal UserContext.remove(); } }
@Configuration public class WebInterceptorAdapter implements WebMvcConfigurer { @Bean public HandlerInterceptor getTokenInterceptor() { return new AuthorizationInterceptor(); } @Override public void configurePathMatch(PathMatchConfigurer configurer) { AntPathMatcher pathMatcher = new AntPathMatcher(); pathMatcher.setCaseSensitive(false); configurer.setPathMatcher(pathMatcher); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(getTokenInterceptor()); } }
UserContext
public class UserContext { private static ThreadLocal<UserInfo> userThread = new ThreadLocal<>(); public static void set(UserInfo userInfo) { userThread.set(userInfo); } public static UserInfo get() { return userThread.get(); } /** * 获取当前登录用户的ID * 未登录返回null * * @return */ public static Long getUserId() { UserInfo user = get(); if (user != null && user.getId() != null) { return user.getId(); } return null; } //防止内存泄漏 public static void remove() { userThread.remove(); } }
UserInfo 对象
@Data public class UserInfo implements Serializable { /** * 主键 */ private Long id; /** * 用户名 */ private String userName; /** * 电话 */ private String tel; }