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指定的对应实现类做服务降级处理,至于是返回何种错误信息或者何种操作就看自己在对应实现类中的定义了

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