Hystrix熔断服务降级

80608145642.png

Hystrix服务降级,其实就是线程池中单个线程障处理,防止单个线程请求时间太长,导致资源长期被占有而得不到释放,从而导致线程池被快速占用完,导致服务崩溃。
Hystrix能解决如下问题:
1.请求超时降级,线程资源不足降级,降级之后可以返回自定义数据
2.线程池隔离降级,分布式服务可以针对不同的服务使用不同的线程池,从而互不影响
3.自动触发降级与恢复
4.实现请求缓存和请求合并

下面我们主要展示一下超时降级
测试1:设置getCourse sleep 3s,打印“getFallback HystrixCommand course.”
测试2:设置getCourse sleep 1s,打印“get course success.”

HystrixCommand实现熔断

public class GetCourseHystrixCommand extends HystrixCommand<String> {
    private CourseService courseService;

    protected GetCourseHystrixCommand(CourseService courseService) {
        super(setter());
        this.courseService= courseService;
    }

    @Override protected String run() throws Exception {
        return courseService.getCourse();
    }

    @Override
    protected String getFallback(){
        return "getFallback HystrixCommand course.";
    }

    private static Setter setter(){
        HystrixCommandGroupKey commandGroupKey= HystrixCommandGroupKey.Factory.asKey("course");
        HystrixCommandProperties.Setter commandProperties= HystrixCommandProperties.Setter()
                .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
                .withFallbackEnabled(true)//是否启用降级
                .withFallbackIsolationSemaphoreMaxConcurrentRequests(10)//设置getFallback并发请求信号量,如果超过信号量值,不会再走直getFallback而直接快速失败
                .withExecutionIsolationThreadInterruptOnFutureCancel(true)
                .withExecutionIsolationThreadInterruptOnTimeout(true)//当隔离策略为Thread时候,当线程超时时,是否中断处理
                .withExecutionTimeoutEnabled(true)//是否启用超时机制
                .withExecutionTimeoutInMilliseconds(2000);//超时时间设置
        return HystrixCommand.Setter.withGroupKey(commandGroupKey)
                .andCommandPropertiesDefaults(commandProperties);
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        GetCourseHystrixCommand courseHystrixCommand= new GetCourseHystrixCommand(new CourseService());
        Future<String> future= courseHystrixCommand.queue();
        System.out.println(future.get());
    }
}


//辅助类
public class CourseService {

    public String getCourse() throws InterruptedException {
        Thread.sleep(3000L);
        return "get course success.";
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容