记录:391
场景:基于Spring Cloud OpenFeign调用微服务Restful接口时,请求头从A服务传递到B服务,可以使用RequestInterceptor接口或者@RequestHeader注解传递请求头信息。
版本:JDK 1.8,SpringBoot 2.6.3,springCloud 2021.0.1
1.使用RequestInterceptor传递请求头信息
1.1关于RequestInterceptor
RequestInterceptor是一个接口,全路径:feign.RequestInterceptor。
RequestInterceptor本质上就是一个拦截器,拦截时机是在OpenFeign调用Restful接口前拦截,因此可以设置请求信息。
使用RequestInterceptor,需实现它的apply(RequestTemplate var1)。换句话说,就是在apply方法中向RequestTemplate对象中注入请求头,
1.2实现RequestInterceptor接口
(1)代码
@Slf4j
@Configuration
public class FeignConfiguration implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
// 1.从前端过来的请求头取信息
RequestAttributes reqAttributes = RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes) reqAttributes).getRequest();
String cityCode = request.getHeader("cityCode");
requestTemplate.header("cityCode", cityCode);
// 2.设置自定义请求头信息
requestTemplate.header("cityNo", "0571");
}
}

文章介绍了在基于SpringCloudOpenFeign的微服务架构中,如何在调用Restful接口时传递请求头信息。第一种方法是使用RequestInterceptor接口,在调用前设置请求头;第二种方法是通过@RequestHeader注解直接在接口方法参数中指定请求头。两种方式都在实际代码示例中得到了详细解释。
最低0.47元/天 解锁文章

7330

被折叠的 条评论
为什么被折叠?



