最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringCloud中分析講解Feign組件添加請(qǐng)求頭有哪些坑梳理

 更新時(shí)間:2022年06月21日 09:33:33   作者:沙礫_  
在spring?cloud的項(xiàng)目中用到了feign組件,簡(jiǎn)單配置過(guò)后即可完成請(qǐng)求的調(diào)用。又因?yàn)橛邢蛘?qǐng)求添加Header頭的需求,查閱了官方示例后,就覺(jué)得很簡(jiǎn)單,然后一頓操作之后調(diào)試報(bào)錯(cuò)...下面我們來(lái)詳細(xì)了解

按官方修改的示例:

#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);
}

提示錯(cuò)誤:

java.lang.IllegalArgumentException: method GET must not have a request body.

分析

通過(guò)斷點(diǎn)debug發(fā)現(xiàn)feign發(fā)請(qǐng)求時(shí)把userInfo參數(shù)當(dāng)成了requestBody來(lái)處理,而okhttp3會(huì)檢測(cè)get請(qǐng)求不允許有body(其他類型的請(qǐng)求哪怕不報(bào)錯(cuò),但因?yàn)椴皇窃O(shè)置到請(qǐng)求頭,依然不滿足需求)。

查閱官方文檔里是通過(guò)Contract(Feign.Contract.Default)來(lái)解析注解的:

Feign annotations define the Contract between the interface and how the underlying client should work. Feign's default contract defines the following annotations:

AnnotationInterface TargetUsage
@RequestLineMethodDefines the HttpMethod and UriTemplate for request. Expressions, values wrapped in curly-braces {expression} are resolved using their corresponding @Param annotated parameters.
@ParamParameterDefines a template variable, whose value will be used to resolve the corresponding template Expression, by name.
@HeadersMethod, TypeDefines 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.
@QueryMapParameterDefines a Map of name-value pairs, or POJO, to expand into a query string.
@HeaderMapParameterDefines a Map of name-value pairs, to expand into Http Headers
@BodyMethodDefines a Template, similar to a UriTemplate and HeaderTemplate, that uses @Param annotated values to resolve the corresponding Expressions.

從自動(dòng)配置類找到使用的是spring cloud的SpringMvcContract(用來(lái)解析@RequestMapping相關(guān)的注解),而這個(gè)注解并不會(huì)處理解析上面列的注解

@Configuration
public class FeignClientsConfiguration {
	@Bean
	@ConditionalOnMissingBean
	public Contract feignContract(ConversionService feignConversionService) {
		return new SpringMvcContract(this.parameterProcessors, feignConversionService);
	}

解決

原因找到了:spring cloud使用了自己的SpringMvcContract來(lái)解析注解,導(dǎo)致默認(rèn)的注解解析方式失效。 解決方案自然就是重新解析處理feign的注解,這里通過(guò)自定義Contract繼承SpringMvcContract再把Feign.Contract.Default解析邏輯般過(guò)來(lái)即可(重載的方法是在SpringMvcContract基礎(chǔ)上做進(jìn)一步解析,否則Feign對(duì)RequestMapping相關(guān)對(duì)注解解析會(huì)失效)

代碼如下(此處只對(duì)@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);
    }

改完馬上進(jìn)行新一頓的操作, 看請(qǐng)求日志已經(jīng)設(shè)置成功,響應(yīng)OK!:

請(qǐng)求: {"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":""}

響應(yīng) {"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 鏈接

(另一種實(shí)現(xiàn)請(qǐng)求頭的方式:實(shí)現(xiàn)RequestInterceptor,但是存在hystrix線程切換的坑)

到此這篇關(guān)于SpringCloud中分析講解Feign組件添加請(qǐng)求頭有哪些坑梳理的文章就介紹到這了,更多相關(guān)SpringCloud Feign組件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 詳解Java中super的幾種用法并與this的區(qū)別

    詳解Java中super的幾種用法并與this的區(qū)別

    這篇文章主要介紹了Java中super的幾種用法并與this的區(qū)別,有需要的朋友可以參考一下
    2013-12-12
  • JavaWeb文件上傳開發(fā)實(shí)例

    JavaWeb文件上傳開發(fā)實(shí)例

    這篇文章主要為大家詳細(xì)介紹了JavaWeb文件上傳開發(fā)實(shí)例,如何進(jìn)行文件上傳操作,感興趣的小伙伴們可以參考一下
    2016-08-08
  • dom4j創(chuàng)建和解析xml文檔的實(shí)現(xiàn)方法

    dom4j創(chuàng)建和解析xml文檔的實(shí)現(xiàn)方法

    下面小編就為大家?guī)?lái)一篇dom4j創(chuàng)建和解析xml文檔的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-06-06
  • SpringAOP實(shí)現(xiàn)自定義接口權(quán)限控制

    SpringAOP實(shí)現(xiàn)自定義接口權(quán)限控制

    本文主要介紹了SpringAOP實(shí)現(xiàn)自定義接口權(quán)限控制,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-11-11
  • MyEclipse10安裝Log4E插件

    MyEclipse10安裝Log4E插件

    這篇文章主要介紹了MyEclipse10安裝Log4E插件的相關(guān)資料,需要的朋友可以參考下
    2017-10-10
  • Pattern.compile函數(shù)提取字符串中指定的字符(推薦)

    Pattern.compile函數(shù)提取字符串中指定的字符(推薦)

    這篇文章主要介紹了Pattern.compile函數(shù)提取字符串中指定的字符,使用的是Java中的Pattern.compile函數(shù)來(lái)實(shí)現(xiàn)對(duì)指定字符串的截取,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-12-12
  • Springboot內(nèi)嵌SQLite配置使用詳解

    Springboot內(nèi)嵌SQLite配置使用詳解

    這篇文章主要介紹了Springboot內(nèi)嵌SQLite配置使用詳解,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-08-08
  • Mybatis動(dòng)態(tài)SQL的實(shí)現(xiàn)示例

    Mybatis動(dòng)態(tài)SQL的實(shí)現(xiàn)示例

    這篇文章主要介紹了Mybatis動(dòng)態(tài)SQL的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • Springboot項(xiàng)目如何獲取所有的接口

    Springboot項(xiàng)目如何獲取所有的接口

    這篇文章主要介紹了Springboot項(xiàng)目如何獲取所有的接口,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Springboot如何加載靜態(tài)圖片

    Springboot如何加載靜態(tài)圖片

    這篇文章主要介紹了Springboot如何加載靜態(tài)圖片,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03

最新評(píng)論

辽源市| 东台市| 扶绥县| 昭觉县| 兴业县| 华容县| 中江县| 云梦县| 明光市| 洛南县| 建水县| 竹北市| 博乐市| 滨州市| 乐清市| 乡宁县| 双辽市| 哈密市| 读书| 临汾市| 灌阳县| 辰溪县| 南丹县| 罗定市| 连州市| 大余县| 刚察县| 修文县| 静安区| 萍乡市| 宁武县| 许昌市| 洛隆县| 中方县| 剑川县| 溧水县| 保康县| 乌兰浩特市| 金寨县| 龙江县| 洪泽县|