设为首页 加入收藏

TOP

[Spring cloud 一步步实现广告系统] 11. 使用Feign实现微服务调用(二)
2019-09-01 23:16:23 】 浏览:26
Tags:Spring cloud 步步 实现 广告 系统 11. 使用 Feign 服务 调用
uot;/search-feign") public class SearchFeignController { /** * 注入我们自定义的FeignClient */ private final ISponsorFeignClient sponsorFeignClient; @Autowired public SearchFeignController(ISponsorFeignClient sponsorFeignClient) { this.sponsorFeignClient = sponsorFeignClient; } @GetMapping(path = "/user/get") public CommonResponse getUsers(@Param(value = "username") String username) { log.info("ad-search::getUsersFeign -> {}", JSON.toJSONString(username)); CommonResponse commonResponse = sponsorFeignClient.getUsers(username); return commonResponse; } }
  • 三部曲之Step 3(加配置,工具类库不需要,添加在具体的微服务中)

我们上面的实例中有一个问题,如果说我们的广告提供服务出现了问题,那么我们通过使用FeignClient 调用的APIsponsorFeignClient.getUsers(username);就会报错,如果长时间报错,会引起大规模的服务错误问题,也就有是我们常说的服务雪崩效应,我们要怎样避免一个服务出错而拖垮整个系统的问题呢?这里我们需要引入一个组件Hystrix来处理服务错误。

  • 三部曲之Step1(加依赖)
    UTOOLS1564468068440.png

从上图我们可以看到,我们引入Feign依赖的时候,它本身已经依赖了Hystrix,根据Maven依赖的传递性,我们可以知道我们自己的服务已经包含了Hystrix的依赖支持,我们可以直接使用了~

  • 三部曲之Step2(加注解) @EnableHystrix // 开启hystrix 断路器
  • 三部曲之Step3(改配置)
feign:
  hystrix:
    enabled: true
  • 使用Hystrix来配置Feign实现调用容错
@Component
public class SponsorClientHystrix implements ISponsorFeignClient {
    @Override
    public CommonResponse<List<AdPlanVO>> getAdPlansUseFeign(AdPlanGetRequestVO requestVO) {
        return new CommonResponse<>(-1, "mscx-ad-sponsor feign & hystrix get plan error.");
    }

    @Override
    public CommonResponse getUsers(String username) {
        return new CommonResponse<>(-1, "mscx-ad-sponsor feign & hystrix get user error.");
    }
}

ISponsorFeignClient类中,添加出错处理类(fallback)

@FeignClient(value = "mscx-ad-sponsor", fallback = SponsorClientHystrix.class)
public interface ISponsorFeignClient {
...

SponsorClientHystrix中,我们要特别注意2点

  1. 该类必须添加@Component注解,以便可以加入Spring 容器中
  2. 该类需要实现ISponsorFeignClientFeign的客户端接口

通过上面的实现,我们的服务在调用过程中,如果发生错误,就会进行服务降级,调用到出错应该调用的默认处理类中的方法,也就实现了我们想要做的短路处理来保护我们的当前服务。

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇[Spring cloud 一步步实现广告系.. 下一篇方法的形式参数是类名的时候如何..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目