- 在之前的文章中使用注解
@HystrixCommand
的fallbackMethod
属性实现回调的。
@Slf4j @Component public class AdditionCommand { @Autowired private AdditionClient additionClient; @HystrixCommand(fallbackMethod = "fallback") public ResponseEntity<ResultData> add(Integer a, Integer b) { // 模拟接口异常 Random random = new Random(); int r = random.nextInt(10); if (r % 2 == 0) { throw new RuntimeException(); } return additionClient.add(a, b); } public ResponseEntity<ResultData> fallback(Integer a, Integer b) { ResultData resultData = new ResultData(); Message message = Message.builder().code(10000).message("xxxx").build(); resultData.setMessage(message); return ResponseEntity.ok(resultData); } }
然后,Feign是以接口的形式进行工作的,本身没有方法体。那么Feign怎么与Hystrix整合呢?
事实上,SpringCloud默认已经为Feign整合了Hystrix,只要添加Hystrix依赖,Feign默认就会用断路器包裹所有方法。
Feign接口定义:
26. import com.gemantic.commons.ResultData; 27. import org.springframework.cloud.netflix.feign.FeignClient; 28. import org.springframework.http.ResponseEntity; 29. import org.springframework.web.bind.annotation.GetMapping; 30. import org.springframework.web.bind.annotation.RequestParam; 31. 32. /** 33. * @author Yezhiwei 34. * @date 17/12/14 35. */ 36. @FeignClient(name = "springcloud-subtraction-service", fallback = SubtractionClientFallBack.class) 37. public interface SubtractionClient { 38. 39. /** 40. * 减法接口 41. * @param a 42. * @param b 43. * @return 44. */ 45. @GetMapping(value = "/sub") 46. ResponseEntity<ResultData> sub(@RequestParam("a") Integer a, @RequestParam("b") Integer b); 47. } 回调实现 SubtractionClient接口: 1. import com.gemantic.commons.ResultData; 2. import org.springframework.http.ResponseEntity; 3. import org.springframework.stereotype.Component; 4. import org.springframework.web.bind.annotation.RequestParam; 5. 6. /** 7. * @author Yezhiwei 8. * @date 17/12/14 9. */ 10. @Component 11. public class SubtractionClientFallBack implements SubtractionClient { 12. @Override 13. public ResponseEntity<ResultData> sub(@RequestParam("a") Integer a, @RequestParam("b") Integer b) { 14. // 这里是实现的回调逻辑! 15. return null; 16. } 17. }
好了,开始测试。but but but 问题来了,访问了几次接口,断路器Hystrix一直不起作用,HystrixDashboard
也没有收到任何统计信息。感觉Feign中并没有启用Hystrix,通过查看文档发现了Hystrix在Feign中的开关配置, 从Disable HystrixCommands For FeignClients By Default (https://github.com/spring-cloud/spring-cloud-netflix/issues/1277) 中知道了产生错误的原因,以及为什么要默认关闭Hystrix。
解决方案,在properties文件中增加feign.hystrix.enabled=true