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(加依赖)
从上图我们可以看到,我们引入Feign依赖的时候,它本身已经依赖了Hystrix,根据Maven依赖的传递性,我们可以知道我们自己的服务已经包含了Hystrix的依赖支持,我们可以直接使用了~
- 三部曲之Step2(加注解)
@EnableHystrix // 开启hystrix 断路器
- 三部曲之Step3(改配置)
feign:
hystrix:
enabled: true
@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点
- 该类必须添加
@Component
注解,以便可以加入Spring 容器中
- 该类需要实现
ISponsorFeignClient
Feign的客户端接口
通过上面的实现,我们的服务在调用过程中,如果发生错误,就会进行服务降级,调用到出错应该调用的默认处理类中的方法,也就实现了我们想要做的短路处理来保护我们的当前服务。