在实际的开发过程中,如果你的项目中引入了鉴权机制,那么使用远程调用的接口时,应当也需要对此次远程调用采取鉴权,但是,fegin自带的请求肯定是不带token的,对此的一个解决方案就是,将请求的token添加到feign的请求之中.
实现
Feign有提供一个接口,RequestInterceptor;只要实现这个接口,简单做一些处理。
@Configuration
public class FeignConfig implements RequestInterceptor {
/**
* Called for every request. Add data using methods on the supplied {@link RequestTemplate}.
*
* @param template
*/
@Override
public void apply(RequestTemplate template) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// 获取请求体
javax.servlet.http.HttpServletRequest request = attributes.getRequest();
// 获取token
String token = request.getHeader("token");
// 注入feign的请求头
template.header("token",token);
}
}
远程调用接口定义
需要指明配置类在@FeignClient
中添加 configuration = FeignConfig.class
属性
@Component
@FeignClient(value = "user-service",configuration = FeignConfig.class)
public interface UserClient {
/**
* 信息
*
* @param userId
* @return {@link Result}
*/
@GetMapping("/admin/users/info/{userId}")
public UserVo info(@PathVariable String userId);
}