使用feign遠程調用接口

項目中開發中,經常會用到調用其他項目的接口 或者第三方接口的情況,以前經常使用的是spring 的restTemplate 或者httpClient,但是使用每次都需要寫一些公共的調用代碼,比較麻煩。
feign 則能夠比較好的解決了這個問題,不是spring cloud 項目也可以使用。

  • 一,是什麼

feign 是Netflix 開發的聲明式的http客戶端,可以幫我們更加方便的調用http接口。在使用時候,就像調用本地方法一樣,創建一個接口,然後在接口上添加一些註解,代碼就可以完成了。spring Cloud 對feign進行了增強,使feign支持spring mvc 註解,並且整合了Ribbon 和Eureka,從而讓Feign的使用更加的方便。

  • 二,怎麼用
  1. 1.添加pom引用
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
         </dependency>
  1. 2.啓動類添加@EnableFeignClients
@SpringBootApplication
@EnableFeignClients
public class DemoApplication {
   
   

    public static void main(String[] args) {
   
   
        SpringApplication.run(DemoApplication.class, args);
    }
}

  1. 3.創建service,添加@feignclient註解
/**
 * @創建人 
 * @創建時間 2020/12/10
 * @描述
 */
@FeignClient(value = "spring-boot-user", url = "http://test-ns.htexam.com/pand/common/mo",
        //fallback = HystrixClientFallBack.class
        fallbackFactory = HystrixClientFallBackFactory.class)
public interface UserFeignClient {
   
   

    @RequestMapping(value = "", method = RequestMethod.GET)
    Object findById();

}

@feignCient 註解中,value和name 是指定的要調用的服務ID,url是指定的訪問的url地址,有時候,feignclient沒有啓動註冊中心,那我們就需要啓動feingclient中的url屬性來表明被調用方。fallBack或fallBackFactory 是方法失敗,可以回退調用的方法。

首先這是一個接口,feign通過動態代理,幫助我們生成實現類,通過value 指定要要調用的服務的名稱。接口中的定義的方法,通過使用spring mvc 的註解,Feign會根據註解生成url,並且返回結果。

  1. 4.創建會退fallBack

    fallbackFactory與fallback方法不能同時使用,這個兩個方法其實都類似於Hystrix的功能,當網絡不通時返回默認的配置數據.

(1)fallBackFactory 方法

@Component
public class HystrixClientFallBackFactory implements FallbackFactory<UserFeignClient> {
   
   

    private Logger logger = LoggerFactory.getLogger(HystrixClientFallBackFactory.class);

    @Override
    public UserFeignClient create(Throwable throwable) {
   
   
      logger.error("failBack reason :{}",throwable.getMessage());
      //若發生錯誤,打印出來
      //failBack reason :status 404 reading UserFeignClient#findById()
        return new UserFeignClient() {
   
   
            @Override
            public Object findById() {
   
   
                StudentEntity studentEntity = StudentEntity.builder().userName("fallBackFactory 默認的用戶名稱").userId(456).age(12).build();
                return studentEntity;
            }
        };
    }
}

fallBack 回退之後,但是想要知道發生fallBack的原因,可以使用Logger打印出來,
logger.error(“fallback reason:{}”,throwable.getMessage());

(2)fallBack方式

直接實現UserFeignClient接口,然後重新servie方法

@Component
public class HystrixClientFallBack  implements  UserFeignClient{
   
   
    @Override
    public Object findById() {
   
   
        StudentEntity studentEntity = StudentEntity.builder().userId(123).userName("默認的用戶姓名").age(12).build();
        return studentEntity;
    }
}

若配置了fallback,需要yml文件中配置,將熔斷打開。

feign:
  hystrix:
    enabled: true # 開啓feign的熔斷功能
    #若爲true,但是未配置fallBack類 FeignPaperService#getMapper() failed and no fallback available.

爲了驗證測試熔斷fallBack機制,我將調用接口的url 改成錯誤的路由,並沒有走到fallback類中去,而是拋錯了。

status 404 reading UserFeignClient#findById()
原因就是未開啓 feign:hystrix:enabled=true

  1. 5.單元測試
@Test
    public void testFeignUserService() {
   
   
        Object object = userFeignClient.findById();
        log.info("object信息是:{}" + object);//返回的是默認的 userName
    }
  • 三,openFeign 和 Feign的區別

    openFeign是Feign的升級版本,相同點:都是遠程調用的組件,裏面度配置了ribbon,都可以進行遠程調用
    不同點:一個是spring-cloud-starter-feign,一個是spring-cloud-starter-openfeign

  • 四, 其他功能

    其他feign還支持負載均衡,Hystrix 熔斷支持,請求壓縮等。
    參考鏈接:
    feign聲明式服務調用
    feign使用大全


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章