SpringCloud中分析讲解Feign组件添加请求头有哪些坑梳理
作者:沙砾_ 发布时间:2023-05-01 19:30:11
按官方修改的示例:
#MidServerClient.java
import feign.Param;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(value = "edu-mid-server")
public interface MidServerClient {
@RequestMapping(value = "/test/header", method = RequestMethod.GET)
@Headers({"userInfo:{userInfo}"})
Object headerTest(@Param("userInfo") String userInfo);
}
提示错误:
java.lang.IllegalArgumentException: method GET must not have a request body.
分析
通过断点debug发现feign发请求时把userInfo参数当成了requestBody来处理,而okhttp3会检测get请求不允许有body(其他类型的请求哪怕不报错,但因为不是设置到请求头,依然不满足需求)。
查阅官方文档里是通过Contract(Feign.Contract.Default)来解析注解的:
Feign annotations define the Contract between the interface and how the underlying client should work. Feign's default contract defines the following annotations:
Annotation | Interface Target | Usage |
---|---|---|
@RequestLine | Method | Defines the HttpMethod and UriTemplate for request. Expressions, values wrapped in curly-braces {expression} are resolved using their corresponding @Param annotated parameters. |
@Param | Parameter | Defines a template variable, whose value will be used to resolve the corresponding template Expression, by name. |
@Headers | Method, Type | Defines a HeaderTemplate; a variation on a UriTemplate. that uses @Param annotated values to resolve the corresponding Expressions. When used on a Type, the template will be applied to every request. When used on a Method, the template will apply only to the annotated method. |
@QueryMap | Parameter | Defines a Map of name-value pairs, or POJO, to expand into a query string. |
@HeaderMap | Parameter | Defines a Map of name-value pairs, to expand into Http Headers |
@Body | Method | Defines a Template, similar to a UriTemplate and HeaderTemplate, that uses @Param annotated values to resolve the corresponding Expressions. |
从自动配置类找到使用的是spring cloud的SpringMvcContract(用来解析@RequestMapping相关的注解),而这个注解并不会处理解析上面列的注解
@Configuration
public class FeignClientsConfiguration {
@Bean
@ConditionalOnMissingBean
public Contract feignContract(ConversionService feignConversionService) {
return new SpringMvcContract(this.parameterProcessors, feignConversionService);
}
解决
原因找到了:spring cloud使用了自己的SpringMvcContract来解析注解,导致默认的注解解析方式失效。 解决方案自然就是重新解析处理feign的注解,这里通过自定义Contract继承SpringMvcContract再把Feign.Contract.Default解析逻辑般过来即可(重载的方法是在SpringMvcContract基础上做进一步解析,否则Feign对RequestMapping相关对注解解析会失效)
代码如下(此处只对@Headers、@Param重新做了解析):
#FeignCustomContract.java
import feign.Headers;
import feign.MethodMetadata;
import feign.Param;
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
import org.springframework.cloud.openfeign.support.SpringMvcContract;
import org.springframework.core.convert.ConversionService;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.*;
import static feign.Util.checkState;
import static feign.Util.emptyToNull;
public class FeignCustomContract extends SpringMvcContract {
public FeignCustomContract(List<AnnotatedParameterProcessor> annotatedParameterProcessors, ConversionService conversionService) {
super(annotatedParameterProcessors, conversionService);
}
@Override
protected void processAnnotationOnMethod(MethodMetadata data, Annotation methodAnnotation, Method method) {
//解析mvc的注解
super.processAnnotationOnMethod(data, methodAnnotation, method);
//解析feign的headers注解
Class<? extends Annotation> annotationType = methodAnnotation.annotationType();
if (annotationType == Headers.class) {
String[] headersOnMethod = Headers.class.cast(methodAnnotation).value();
checkState(headersOnMethod.length > 0, "Headers annotation was empty on method %s.", method.getName());
data.template().headers(toMap(headersOnMethod));
}
}
@Override
protected boolean processAnnotationsOnParameter(MethodMetadata data, Annotation[] annotations, int paramIndex) {
boolean isMvcHttpAnnotation = super.processAnnotationsOnParameter(data, annotations, paramIndex);
boolean isFeignHttpAnnotation = false;
for (Annotation annotation : annotations) {
Class<? extends Annotation> annotationType = annotation.annotationType();
if (annotationType == Param.class) {
Param paramAnnotation = (Param) annotation;
String name = paramAnnotation.value();
checkState(emptyToNull(name) != null, "Param annotation was empty on param %s.", paramIndex);
nameParam(data, name, paramIndex);
isFeignHttpAnnotation = true;
if (!data.template().hasRequestVariable(name)) {
data.formParams().add(name);
}
}
}
return isMvcHttpAnnotation || isFeignHttpAnnotation;
}
private static Map<String, Collection<String>> toMap(String[] input) {
Map<String, Collection<String>> result =
new LinkedHashMap<String, Collection<String>>(input.length);
for (String header : input) {
int colon = header.indexOf(':');
String name = header.substring(0, colon);
if (!result.containsKey(name)) {
result.put(name, new ArrayList<String>(1));
}
result.get(name).add(header.substring(colon + 1).trim());
}
return result;
}
}
#FeignCustomConfiguration.java
import feign.Contract;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.ConversionService;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class FeignCustomConfiguration {
@Autowired(required = false)
private List<AnnotatedParameterProcessor> parameterProcessors = new ArrayList<>();
@Bean
@ConditionalOnProperty(name = "feign.feign-custom-contract", havingValue = "true", matchIfMissing = true)
public Contract feignContract(ConversionService feignConversionService) {
return new FeignCustomContract(this.parameterProcessors, feignConversionService);
}
改完马上进行新一顿的操作, 看请求日志已经设置成功,响应OK!:
请求: {"type":"OKHTTP_REQ","uri":"/test/header","httpMethod":"GET","header":"{"accept":["/"],"userinfo":["{"userId":"sssss","phone":"13544445678],"x-b3-parentspanid":["e49c55484f6c19af"],"x-b3-sampled":["0"],"x-b3-spanid":["1d131b4ccd08d964"],"x-b3-traceid":["9405ce71a13d8289"]}","param":""}
响应 {"type":"OKHTTP_RESP","uri":"/test/header","respStatus":0,"status":200,"time":5,"header":"{"cache-control":["no-cache,no-store,max-age=0,must-revalidate"],"connection":["keep-alive"],"content-length":["191"],"content-type":["application/json;charset=UTF-8"],"date":["Fri,11Oct201913:02:41GMT"],"expires":["0"],"pragma":["no-cache"],"x-content-type-options":["nosniff"],"x-frame-options":["DENY"],"x-xss-protection":["1;mode=block"]}"}
feign官方链接
spring cloud feign 链接
(另一种实现请求头的方式:实现RequestInterceptor,但是存在hystrix线程切换的坑)
来源:https://juejin.cn/post/6844903961653149709


猜你喜欢
- 委托定义类型,类型指定特定方法签名。可将满足此签名的方法(静态或实例)分配给该类型的变量,然后(使用适当参数)直接调用该方法,或将其作为参数
- 由于是多态对象,基类类型的变量可以保存派生类型。 要访问派生类型的实例成员,必须将值强制转换 * 生类型。 但是,强制转换会引发 Invali
- java中的set接口有如下的特点:不允许出现重复元素;集合中的元素位置无顺序;有且只有一个值为null的元素。因为java中的set接口模
- 1. 在原有工程目录右键-> new ->Module->:2. 选择library:3. 一路next,最后finish
- Spring P标签的使用Spring的p标签是基于XML Schema的配置方式,目的是为了简化配置方式。由于Spring的p标签是spr
- 前提前面写过一篇关于Environment属性加载的源码分析和扩展,里面提到属性的占位符解析和类型转换是相对复杂的,这篇文章就是要分析和解读
- 这两天做了一个项目,发现标签不能更改任意一个标签的字体的颜色,需求如同置前标签,然后就对tagcloudeview稍做修改做了这么一个dem
- 1. 你知道线程安全问题吗?线程安全问题:一般指在多线程模式下,多个线程对同一个共享数据进行操作时,第一个线程还没来得及更新共享数据,从而导
- C++11中的std::packaged_task是个模板类。std::packaged_task包装任何可调用目标(函数、lambda表达
- 本文实例讲述了Android编程调用Camera和相册功能。分享给大家供大家参考,具体如下:xml:<LinearLayout xml
- 这篇文章主要介绍了Spring Cache手动清理Redis缓存,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值
- 本文实例讲述了Java使用Jdbc连接Oracle执行简单查询操作。分享给大家供大家参考,具体如下:Java Jdbc 连接 Oracle
- 一 概述GC(Garbage Collection),在程序运行过程中内存空间是有限的,为了更好的的使用有限的内存空间,GC会将不再使用的对
- 系列文章已完成,目录如下:jdk-logging log4j logback日志系统实现机制原理介绍commons-lo
- config.json 文件内容如下{"Data": {"DefaultConnection": {
- int a = 5; int b = 30; Console.WriteLine(a^b);&n
- 这篇文章主要介绍了java多线程关键字final和static详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价
- 本篇博客要分享的一个效果是实现广告Banner轮播效果,这个效果也比较常见,一些视频类应用就经常有,就拿360影视大全来举例吧:
- 如何给请求添加header背景:在集成了swagger的项目中,调用后台接口往往会经过一些自定义的 * ,而 * 加了token限制的话,直
- 本文实例为大家分享了UnityShader实现运动模糊的具体代码,供大家参考,具体内容如下1.此代码挂在摄像机上,使摄像机运动起来using