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 20 Java/Android
springboot如何初始化执行sql语句
Jun 22 Java/Android
elasticSearch-api的具体操作步骤讲解
Jun 28 Java/Android
SpringBoot集成Druid连接池连接MySQL8.0.11
Jul 02 Java/Android
dubbo集成zipkin获取Traceid的实现
Jul 26 Java/Android
简述Java中throw-throws异常抛出
Aug 07 Java/Android
java调用Restful接口的三种方法
Aug 23 Java/Android
SpringCloud之@FeignClient()注解的使用方式
Sep 25 Java/Android
Spring this调用当前类方法无法拦截的示例代码
Mar 20 Java/Android
SpringBoot 集成短信和邮件 以阿里云短信服务为例
Apr 22 Java/Android
java实现自定义时钟并实现走时功能
Jun 21 Java/Android
SpringBoot接入钉钉自定义机器人预警通知
Jul 15 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
与数据库连接
2006/10/09 PHP
注意:php5.4删除了session_unregister函数
2013/08/05 PHP
ThinkPHP利用PHPMailer实现邮件发送实现代码
2013/09/26 PHP
typecho插件编写教程(六):调用接口
2015/05/28 PHP
PHP实现的oracle分页函数实例
2016/01/25 PHP
Linux php 中文乱码的快速解决方法
2016/05/13 PHP
PHP使用两个栈实现队列功能的方法
2018/01/15 PHP
PHP生成随机数的方法总结
2018/03/01 PHP
详细对比php中类继承和接口继承
2018/10/11 PHP
jQuery '行 4954 错误: 不支持该属性或方法' 的问题解决方法
2011/01/19 Javascript
js jquery分别实现动态的文件上传操作按钮的添加和删除
2014/01/13 Javascript
七个很有意思的PHP函数
2014/05/12 Javascript
AngularJs 国际化(I18n/L10n)详解
2016/09/01 Javascript
基于js 本地存储(详解)
2017/08/16 Javascript
用element的upload组件实现多图片上传和压缩的示例代码
2019/02/12 Javascript
利用Webpack实现小程序多项目管理的方法
2019/02/25 Javascript
详解微信小程序开发聊天室—实时聊天,支持图片预览
2019/05/20 Javascript
vue实现行列转换的一种方法
2019/08/06 Javascript
详解小程序横屏方案对比
2020/06/28 Javascript
Javascript中Math.max和Math.max.apply的区别和用法详解
2020/08/24 Javascript
python里大整数相乘相关技巧指南
2014/09/12 Python
Python中List.count()方法的使用教程
2015/05/20 Python
python字符串连接方法分析
2016/04/12 Python
python中闭包Closure函数作为返回值的方法示例
2017/12/17 Python
简单谈谈python基本数据类型
2018/09/26 Python
在Python中定义一个常量的方法
2018/11/10 Python
python文档字符串(函数使用说明)使用详解
2019/07/30 Python
用python实现一个简单的验证码
2020/12/09 Python
英国高档百货连锁店:John Lewis
2017/11/20 全球购物
北京一家公司的.net开发工程师笔试题
2012/04/17 面试题
2014年中班元旦活动方案
2014/02/14 职场文书
道德之星事迹材料
2014/05/03 职场文书
群众路线教育实践活动对照检查材料思想汇报(副处级领导)
2014/10/04 职场文书
领导走群众路线整改措施思想汇报
2014/10/12 职场文书
酒店辞职书怎么写
2015/02/26 职场文书
聊聊Lombok中的@Builder注解使用教程
2021/11/17 Java/Android