springcloud Hystrix簡單使用

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章