实现思路:
1:准备一个ThreadLocal变量,供线程之间共享。
2:每个微服务对所有过来的Feign调用进行过滤,然后从请求头中获取User用户信息,并存在ThreadLocal变量中。
3:每个微服务在使用FeignClient调用别的微服务时,先从ThreadLocal里面取出user信息,并放在request的请求头中。
4:封装为一个注解,在启动类上标记即可。
代码样例:
1:ThreadLocal工具类 :UserInfoContext
packagecom.test.domi.common.system;importcom.test.domi.dao.UserInfo;public classUserInfoContext {private static ThreadLocal userInfo = new ThreadLocal();public static String KEY_USERINFO_IN_HTTP_HEADER = "X-AUTO-FP-USERINFO";publicUserInfoContext() {
}public staticUserInfo getUser(){return(UserInfo)userInfo.get();
}public static voidsetUser(UserInfo user){
userInfo.set(user);
}
}
2:准备承载用户信息的userInfo实体类(代码略)
3:编写拦截器 : TransmitUserInfoFeighClientIntercepter