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 16 Java/Android
JavaWeb Servlet实现网页登录功能
Jul 04 Java/Android
springboot集成springCloud中gateway时启动报错的解决
Jul 16 Java/Android
SpringBoot实现quartz定时任务可视化管理功能
Aug 30 Java/Android
Java 超详细讲解设计模式之中的抽象工厂模式
Mar 25 Java/Android
springboot layui hutool Excel导入的实现
Mar 31 Java/Android
详解Alibaba Java诊断工具Arthas查看Dubbo动态代理类
Apr 08 Java/Android
Android 界面一键变灰 深色主题工具类
Apr 28 Java/Android
Android开发之底部导航栏的快速实现
Apr 28 Java/Android
openGauss数据库JDBC环境连接配置的详细过程(Eclipse)
Jun 01 Java/Android
SpringBoot使用AOP实现统计全局接口访问次数详解
Jun 16 Java/Android
Spring中bean集合注入的方法详解
Jul 07 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 XML数据解析代码
2010/05/26 PHP
PHP判断远程url是否有效的几种方法小结
2011/10/08 PHP
使用Thinkphp框架开发移动端接口
2015/08/05 PHP
PHP响应post请求上传文件的方法
2015/12/17 PHP
php array_values 返回数组的所有值详解及实例
2016/11/12 PHP
javascript模仿msgbox提示效果代码
2008/06/10 Javascript
ExtJs扩展之GroupPropertyGrid代码
2010/03/05 Javascript
js数字转换为float,取N位小数
2014/02/08 Javascript
javaScript年份下拉列表框内容为当前年份及前后50年
2014/05/28 Javascript
jQuery实现的淡入淡出二级菜单效果代码
2015/09/15 Javascript
js实现消息滚动效果
2017/01/18 Javascript
完美的js图片轮换效果
2017/02/05 Javascript
微信小程序 this和that详解及简单实例
2017/02/13 Javascript
Bootstrap 3 按钮标签实例代码
2017/02/21 Javascript
Vue2.0实现将页面中表格数据导出excel的实例
2017/08/09 Javascript
Vue+mui实现图片的本地缓存示例代码
2018/05/24 Javascript
手淘flexible.js框架使用和源代码讲解小结
2018/10/15 Javascript
在Vue环境下利用worker运行interval计时器的步骤
2019/08/01 Javascript
JS 创建对象的模式实例小结
2020/04/28 Javascript
Python实现的企业粉丝抽奖功能示例
2019/07/26 Python
将python包发布到PyPI和制作whl文件方式
2019/12/25 Python
python入门之井字棋小游戏
2020/03/05 Python
Python爬虫爬取百度搜索内容代码实例
2020/06/05 Python
tensorflow图像裁剪进行数据增强操作
2020/06/30 Python
Python基于traceback模块获取异常信息
2020/07/23 Python
Java中有几种方法可以实现一个线程?用什么关键字修饰同步方法?stop()和suspend()方法为何不推荐使用?
2015/08/04 面试题
中学生个人自我评价
2014/02/06 职场文书
环卫工人先进事迹材料
2014/06/02 职场文书
就业协议书样本
2014/08/20 职场文书
最美护士演讲稿
2014/08/27 职场文书
2014年人力资源部工作总结
2014/11/19 职场文书
平遥古城导游词
2015/02/03 职场文书
第一节英语课开场白
2015/06/01 职场文书
难以忽视的真相观后感
2015/06/05 职场文书
Python+Selenium自动化环境搭建与操作基础详解
2022/03/13 Python
winserver2019安装软件一直卡在应用程序正在为首次使用做准备
2022/06/10 Servers