Hystrix入门教程

一·什么是Hystrix?Hystrix有什么作用?使用Hystrix有哪些适用场景

Hystrix是springCloud的组件之一,Hystrix 可以让我们在分布式系统中对服务间的调用进行控制
加入一些调用延迟或者依赖故障的容错机制。Hystrix 通过将依赖服务进行资源隔离
进而阻止某个依赖服务出现故障时在整个系统所有的依赖服务调用中进行蔓延;
同时Hystrix 还提供故障时的 fallback 降级机制。
通过这些方法帮助我们提升分布式系统的可用性和稳定性。
在高并发访问下,这些依赖的稳定性与否对系统的影响非常大,
但是依赖有很多不可控问题:如网络连接缓慢,资源繁忙,暂时不可用,服务脱机等.

二·导入Hystrix相关依赖

        <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

三·在启动类上加上@EnableHystrix

@SpringBootApplication
@EnableFeignClients
@EnableApolloConfig
@ComponentScan(basePackages = "com.demo.Hystrix")
@EnableHystrix
public class ApiApplication extends SpringBootServletInitializer {
public static void main(String[] args) { SpringApplication.run(ApiApplication.class, args); }

四·在需要限流的方法中使用Hystrix

        @HystrixCommand(groupKey="test-provider",
threadPoolKey="test-provider",
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "20"),//线程池大小
@HystrixProperty(name = "maximumSize", value = "30"),//最大线程池大小
@HystrixProperty(name = "maxQueueSize", value = "20"),//最大队列长度
@HystrixProperty(name = "keepAliveTimeMinutes", value = "2")//线程存活时间
},commandProperties = {
@HystrixProperty(name = "execution.isolation.strategy",value = "THREAD"),
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "60000" ),
//此处有坑,若中断时间不设置,上面所有参数都可能失效
@HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout",value = "300000" )
},
//fallbackMethod必须重写,否则直接进入fallback方法中!!!!!!
//此处的testfallback,为第五步中重写的方法!!!!!!
fallbackMethod = "testfallback") @ApiOperation(value = "Hystrix测试接口")
@PostMapping("/testHystrix")
@Log(value = "Hystrix测试接口")
public DefaultResponse<WeekendFlightCardCancelFrontResponse> weekendFlightCardCancelFront(@RequestBody WeekendFlightCardCancelFrontRequestVO req) {
//
......
}

五·重写fallback方法

     public DefaultResponse<Response> unlimitedFlightCreateOrderfallback(HttpServletRequest request, HttpServletResponse response, @RequestBody UnlimitedFlightCreateOrderReq req) {
DefaultResponse defaultResp = new DefaultResponse();
defaultResp.setCode(Integer.parseInt(ServiceStatus.RankFAIL.getCode()));
defaultResp.setMessage("系统繁忙,请稍后再试");
return defaultResp;
}

六· 使用总结,此处介绍三个使用过程中的三个大坑

1.必须设置中断时间,若不设置所有参数都可能失效

2.第四步中的@HystrixCommand等注解只能在service层中使用,在controller中使用,hystrix的限流作用会失效

3.必须重写fallbackMethod的fallback方法,不重写的话默认直接进入fallback方法

05-12 06:13