SpringBoot 集成Feign的使用

前言:最近項(xiàng)目中經(jīng)常用到Feign進(jìn)行服務(wù)端之前的調(diào)用,因此小小總結(jié)一下
1. Feign介紹

Feign是Netflix公司開源的輕量級rest客戶端,使用Feign可以非常方便的實(shí)現(xiàn)Http 客戶端。Spring Cloud引入Feign并且集成了Ribbon實(shí)現(xiàn)客戶端負(fù)載均衡調(diào)用。

2. pom.xml

不寫入版本號的話會引入和springboot版本號相匹配的版本

<dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
3. 啟動類加入注解 @EnableFeignClients
@SpringBootApplication
@EnableFeignClients // Feign注解
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
}
4. 添加Feign配置文件(如果不添加此配置文件會報(bào)如下錯誤)

錯誤信息: No qualifying bean of type ‘org.springframework.boot.autoconfigure.http.HttpMessag

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;

import java.util.stream.Collectors;

/**
 * feign的http客戶端配置
 */
@Configuration
public class FeignConfig {
    /**
    *No qualifying bean of type ‘org.springframework.boot.autoconfigure.http.HttpMessage
    */
    @Bean
    @ConditionalOnMissingBean
    public HttpMessageConverters messageConverters(ObjectProvider<HttpMessageConverter<?>> converters) {
        return new HttpMessageConverters(converters.orderedStream().collect(Collectors.toList()));
    }
  
}
5. 如果需要傳遞header參數(shù),需要下述配置文件

bootstrap.yml 增加配置

  • 設(shè)置hystrix的隔離策略
    hystrix.command.default.execution.isolation.strategy = SEMAPHORE
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * feign的header配置
 */
@Configuration
public class FeignHeaderConfig {

    //feign請求轉(zhuǎn)發(fā)是需要從原請求頭復(fù)制的header信息
    final String[] copyHeaders = new String[]{"cookie"};
    /**
     * 重寫后feign轉(zhuǎn)發(fā)請求會攜帶原請求的Head信息
     */
    private class FeignBasicAuthRequestInterceptor implements RequestInterceptor {
        @Override
        public void apply(RequestTemplate requestTemplate) {
            // SystemConstant.COOKIE="Cookie"
            // new DefaultTokenHandler().getTokenInCookie() 為獲取到的Cookie信息
            /**
             spring-boot-starter-webflux 框架走下述方法
             <dependency>
                 <groupId>org.springframework.boot</groupId>
                 <artifactId>spring-boot-starter-webflux</artifactId>
             </dependency>
             */
            requestTemplate.header(SystemConstant.COOKIE, new DefaultTokenHandler().getTokenInCookie());


            /**
             spring-boot-starter-web 框架走下面注釋方法
             <dependency>
                 <groupId>org.springframework.boot</groupId>
                 <artifactId>spring-boot-starter-web</artifactId>
             </dependency>
             
             
             */
            /*
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    while (headerNames.hasMoreElements()) {
                        String name = headerNames.nextElement();
                        String values = request.getHeader(name);
                        if (iscopy(name)) {
                            requestTemplate.header(name, values);
                        }
                    }
                }
            }
            */
        }
    }

    /**
     * @param name
     * @return
     */
    private Boolean iscopy(String name) {
        for (String header : copyHeaders) {
            if (header.equals(name)) {
                return true;
            }
        }
        return false;
    }

    /**
     * feign請求攔截器
     *
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new FeignBasicAuthRequestInterceptor();
    }
    
    /**
     * 開啟feign調(diào)用日志打印的debug模式
     *
     * @return
     */
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}
6. 在Feign客戶端中配置
  • FeignTest.class 客戶端調(diào)用類
/**
 * 發(fā)布用戶信息查詢相關(guān)的接口
 */
@FeignClient(value = "base", configuration = FeignHeaderConfig.class, contextId = "FeignTest", fallbackFactory = FeignTestFactory.class)
public interface FeignTest {

    /**
     * 增量更新用戶信息
     *
     * @param info
     */
    @PostMapping("user")
    public BaseResponse user(@RequestBody Info info);
}
  • FeignTestFactory.class 異常處理的工廠類
/**
 * 異常處理的工廠類
 */
@Component
public class FeignTestFactory<T> implements FallbackFactory<T>, LoggerBase {

    @Override
    public T create(Throwable cause) {
        if (cause.getMessage() != null)
            error("feign接口調(diào)用異常,{}", cause.getMessage());
        return (T) new TestFallBackImp(cause.getMessage());
    }
}
  • TestFallBackImp.class 服務(wù)降級處理類
/**
 * 服務(wù)降級處理類
 */
public class TestFallBackImp implements FeignTest {

    String errMsg;

    public TestFallBackImp(String errMsg) {
        this.errMsg = errMsg;
    }

    @Override
    public BaseResponse user(Info info) {
        return new BaseResponse().err(errMsg);
    }
}
至此,F(xiàn)eign已經(jīng)配置好了
其他錯誤
  • The bean 'XXX.FeignClientSpecification', defined in null, could not be registered
    原因:2.1.0以上版本的,將不再默認(rèn)支持 FeignClient 的name屬性 的相同名字。
    即 :多個接口上的@FeignClient(“相同服務(wù)名”)會報(bào)錯,overriding is disabled(覆蓋 是 禁止的/關(guān)閉的)。
    可以添加配置
    spring.main.allow-bean-definition-overriding=true
    閱讀源碼后,發(fā)現(xiàn)也可以把 contextId 設(shè)置成不一樣的
希望對你有所幫助
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容