SpringCloud中分析讲解Feign组件添加请求头有哪些坑梳理


Posted in Java/Android onJune 21, 2022
目录

按官方修改的示例:

#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线程切换的坑)

到此这篇关于SpringCloud中分析讲解Feign组件添加请求头有哪些坑梳理的文章就介绍到这了,更多相关SpringCloud Feign组件内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!


Tags in this post...

Java/Android 相关文章推荐
Java方法重载和方法重写的区别到底在哪?
Jun 11 Java/Android
Java实现简易的分词器功能
Jun 15 Java/Android
Java常用工具类汇总 附示例代码
Jun 26 Java/Android
图解排序算法之希尔排序Java实现
Jun 26 Java/Android
详解Java七大阻塞队列之SynchronousQueue
Sep 04 Java/Android
SpringBoot+Redis实现布隆过滤器的示例代码
Mar 17 Java/Android
Java详细解析==和equals的区别
Apr 07 Java/Android
Android开发之WECHAT微信小程序路由跳转的两种形式
Apr 12 Java/Android
Android studio 简单计算器的编写
May 20 Java/Android
java获取一个文本文件的编码(格式)信息
Sep 23 Java/Android
Java Redisson多策略注解限流
Sep 23 Java/Android
Mybatis-plus配置分页插件返回统一结果集
SpringCloud超详细讲解Feign声明式服务调用
Jun 21 #Java/Android
使用Postman测试需要授权的接口问题
Jun 21 #Java/Android
springboot集成redis存对象乱码的问题及解决
Jun 16 #Java/Android
SpringBoot使用AOP实现统计全局接口访问次数详解
Jun 16 #Java/Android
Java中的Kotlin 内部类原理
Jun 16 #Java/Android
Spring Security动态权限的实现方法详解
You might like
php Static关键字实用方法
2010/06/04 PHP
解析使用substr截取UTF-8中文字符串出现乱码的问题
2013/06/20 PHP
php array_pop 删除数组最后一个元素实例
2016/11/02 PHP
thinkPHP框架中layer.js的封装与使用方法示例
2019/01/18 PHP
本地图片预览(支持IE6/IE7/IE8/Firefox3)经验总结
2013/03/25 Javascript
如何使用Javascript正则表达式来格式化XML内容
2013/07/04 Javascript
删除select中所有option选项jquery代码
2013/08/12 Javascript
javascript预加载图片、css、js的方法示例介绍
2013/10/14 Javascript
setTimeout()与setInterval()方法区别介绍
2013/12/24 Javascript
一个css与js结合的下拉菜单支持主流浏览器
2014/10/08 Javascript
JavaScript实现关键字高亮功能
2014/11/12 Javascript
javascript实现显示和隐藏div方法汇总
2015/08/14 Javascript
Bootstrap3制作搜索框样式的方法
2016/07/11 Javascript
jQuery实现公告新闻自动滚屏效果实例代码
2016/07/14 Javascript
Bootstrap基本组件学习笔记之下拉菜单(7)
2016/12/07 Javascript
jQuey将序列化对象在前台显示地实现代码(方法总结)
2016/12/13 Javascript
jQuery实现在新增加的元素上添加事件方法案例分析
2017/02/09 Javascript
Vue中Quill富文本编辑器的使用教程
2018/09/21 Javascript
vue中echarts图表大小适应窗口大小且不需要刷新案例
2020/07/19 Javascript
[46:57]EG vs Winstrike 2018国际邀请赛小组赛BO2 第二场 8.18
2018/08/19 DOTA
[04:46]2018年度玩家喜爱的电竞媒体-完美盛典
2018/12/16 DOTA
10款最好的Web开发的 Python 框架
2015/03/18 Python
python中日期和时间格式化输出的方法小结
2015/03/19 Python
Python中的高级函数map/reduce使用实例
2015/04/13 Python
Python实现多态、协议和鸭子类型的代码详解
2019/05/05 Python
pytorch模型存储的2种实现方法
2020/02/14 Python
详解Windows下PyCharm安装Numpy包及无法安装问题解决方案
2020/06/18 Python
python实现简单猜单词游戏
2020/12/24 Python
毕业生个人求职信范例分享
2013/12/17 职场文书
关于廉洁的广播稿
2014/01/30 职场文书
给校长的建议书500字
2014/05/15 职场文书
不尊敬老师检讨书范文
2014/11/19 职场文书
升职感谢信
2015/01/22 职场文书
超搞笑婚前保证书
2015/05/08 职场文书
十大动画制作软件,Adobe产品上榜两款,第一是行业标准软件
2022/03/18 杂记
一文搞懂PHP中的抽象类和接口
2022/05/25 PHP