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;
}

猜你喜欢

转载自blog.csdn.net/wdz985721191/article/details/104915127
今日推荐