1、引入gav
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
2、feign接口註解添加fallback
@FeignClient(value = "服務名",fallback = FeignCustomerHystrix.class) public interface FeignCustomerService{ @RequestMapping(value = "/customer/findCustomer", method = RequestMethod.GET) YJResult findCustomer(@RequestParam("id") Long id); }
FeignCustomerHystrix實現FeignCustomerService中的方法
@Component public class FeignCustomerHystrix implements FeignCustomerService { private Logger log = LoggerFactory.getLogger(CustomerServiceImpl.class); @Override public YJResult findCustomer(Long id) { log.info("-----------------------findCustomer空卡項目調用其他服務失敗輸出-----------------"); return YJResult.error(1005, "服務調用失敗"); } }
3、編寫測試類
@Override public Customer getCutomerById(Long customerId) { // "服務名"如果出現宕機、超時、異常customer均會返回 return YJResult.error(1005, "服務調用失敗");不會影響其他服務調用 YJResult customer = feignCustomerService.findCustomer(customerId); if (customer.getCode() == 1000) { Object data = customer.getData(); if (!ObjectUtils.isEmpty(data) && !data.equals("null")) { Customer entity = JSONObject.parseObject(data.toString(), Customer.class); return entity; } } return null; }