Feign調用微服務和hystrix的服務降級處理

企業級開發中一般使用feign而不用ribbon,不過feign也是基於ribbon開發的,支持註解。

1、application添加註解開啓feign

2、創建接口client

package cn.bestriven.www.client;

import cn.bestriven.www.client.vo.AdPlan;
import cn.bestriven.www.client.vo.AdPlanGetRequest;
import cn.bestriven.www.vo.CommonResponse;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

/**
 * @Author: liufan
 * @Date: 2019/8/20 13:43
 * @Description:
 */
@FeignClient(value = "eureka-client-ad-sponsor")
public interface SponserClient {
    @RequestMapping(value = "/ad-sponsor/get/adPlan",method = RequestMethod.POST)
    CommonResponse<List<AdPlan>> getAdPlans(@RequestBody AdPlanGetRequest request);
}

這裏調用的是eureka-client-ad-sponsor模塊,所以只需要在@FeignClient註解中註明value爲對應的微服務名,然後requestMapping中的value註明對應模塊下方法的路徑,這裏由於eureka-client-ad-sponsor模塊設置了contextpath所以需要在方法前加上對應的ad-sponsor前綴

3、在controller中注入接口


接口注入後在業務中直接調用對應方法即可

4、斷路器hystrix的服務降級

4.1、創建服務調用接口SponserClient的實現類

/**
 * @Author: liufan
 * @Date: 2019/8/20 13:51
 * @Description:
 */
@Component
public class SponsorClientHystrix implements SponserClient{
    @Override
    public CommonResponse<List<AdPlan>> getAdPlans(AdPlanGetRequest request) {
        return new CommonResponse<>(-1,"eureka-client-ad-sponsor error");
    }
}

4.2、對@FeignClient註解添加fallback屬性配置服務降級


此時如果@FeignClient註解的微服務調用出錯,則會轉到fallback指定的對應實現類做服務降級處理,至於是返回何種錯誤信息或者何種操作就看自己在對應實現類中的定義了

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