fegin服务之前传递用户信息

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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值