hystrix的简单使用

发布时间 2023-07-07 14:31:10作者: 城北左少爷

hystrix是微服务中的一个容错保护组件,用来对调用方请求另一服务时的超时,异常的降级保护。

一。.全局配置。

在项目中我们不会单独使用hystrix,一般是利用Feign对hystrix的封装。

1.开启 feign 对于 hystrix 的支持

feign.hystrix.enabled=true

2.全局配置

对feign客户端接口编写一个实现类即可

/**
 * @Description
 * @Author zhl
 * @Date 2023/7/7 9:26
 */
@Component
public class CommonServiceFailback implements CommonService {

    @Override
    public Response getYearList() {
        return Response.fail("haishishibai哈哈哈");
    }
}

指定feign客户端接口的hystrix异常返回类

/**
 * @Description
 * @Author zhl
 * @Date 2023/5/31 16:18
 */
@FeignClient(name = "flowershop-common", fallback = CommonServiceFailback.class)
public interface CommonService {

    @RequestMapping("/common/getYearList")
    Response getYearList();
}

hystrix的默认超时时间为1000ms,可以对其配置:

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds = 2000

3.测试

将Common服务停掉或者将其 getYearList()方法中休眠5秒。调用主服务

 

二.单独使用。

 在 Controller层使用。加入注解

@HystrixCommand(fallbackMethod = "getShopFall")

 2.编写异常返回方法 getShopFall() 

    public Response<?> getShopFall() throws Exception {
        return Response.success("err");
    }

3.测试