微服务架构之容错Hystrix

文章首发于公众号:松花皮蛋的黑板报
做者就任于京东,在稳定性保障、敏捷开发、高级JAVA、微服务架构有深刻的理解nginx

clipboard.png

1、容错的必要性
假设单体应用可用率为99.99%,即便拆分后每一个微服务的可用率仍是保持在99.99%,整体的可用率仍是降低的。由于凡是依赖均可能会失败,凡是资源都是有限制的,另外网络并不可靠。有可能一个很不起眼的微服务模块高延迟最后致使总体服务不可用编程

2、容错的基本模块
一、主动超时,通常设置成2秒或者5秒超时时间
二、服务降级,通常会降级成直接跳转到静态CDN托底页或者提示活动太火爆,以避免开天窗
三、限流,通常使用令牌机制限制最大并发数
四、隔离,对不一样依赖进行隔离,容器CPU绑核就是一种隔离措施
五、弹性熔断,错误数达到必定阀值后,开始拒绝请求,健康检查发现恢复后再次接受请求
3、Hystrix主要概念
Hystrix流程后端

clipboard.png

想要使用Hystrix,只须要继承HystrixCommand或者HystrixObservableCommand并重写业务逻辑方法便可,区别在于HystrixCommand.run()返回一个结果或者异常,HystrixObservableCommand.construct()返回一个Observable对象缓存

编者按:关于反应式编程可参考文章Flux反应式编程结合多线程实现任务编排网络

Hystrix真正执行命令逻辑是经过execute()、queue()、observe()、toObservable()的其中一种,区别在于execute是同步阻塞的,queue经过myObservable.toList().toBlocking().toFuture()实现异步非阻塞,observe是事件注册前执行,toObservable是事件注册后执行,后二者是基于发布和订阅响应式的调用 多线程

clipboard.png

每一个熔断器默认维护10个bucket,每秒一个bucket,每一个bucket记录成功,失败,超时,拒绝的状态,默认错误超过50%且10秒内超过20个请求才进行中断拦截。当断路器打开时,维护一个窗口,每过一个窗口时间,会放过一个请求以探测后端服务健康状态,若是已经恢复则断路器会恢复到关闭状态架构

当断路器打开、线程池提交任务被拒绝、信号量得到被拒绝、执行异常、执行超时任一状况发生都会触发降级fallBack,Hystrix提供两种fallBack方式,HystrixCommand.getFallback()和HystrixObservableCommand.resumeWithFallback()并发

4、线程和信号量隔离异步

clipboard.png

一、线程隔离,针对不一样的服务依赖建立线程池
二、信号量隔离,本质是一个共享锁。当信号量中有可用的许可时,线程能获取该许可(seaphore.acquire()),不然线程必须等待,直到有可用的许可为止。线程用完必须释放(seaphore.release())不然其余线程永久等待ide

clipboard.png

5、Hystrix主要配置项

clipboard.png

6、使用
一、请求上下文,下面将要提到的请求缓存、请求合并都依赖请求上下文,咱们能够在拦截器中进行管理

public class HystrixRequestContextServletFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
     throws IOException, ServletException {
        HystrixRequestContext context = HystrixRequestContext.initializeContext();
        try {
            chain.doFilter(request, response);
        } finally {
            context.shutdown();
        }
    }
}

二、请求缓存,减小相同参数请求后端服务的开销,须要重写getCacheKey方法返回缓存key

public class CommandUsingRequestCache extends HystrixCommand<Boolean> {

    private final int value;

    protected CommandUsingRequestCache(int value) {
        super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
        this.value = value;
    }

    @Override
    protected Boolean run() {
        return value == 0 || value % 2 == 0;
    }

    @Override
    protected String getCacheKey() {
        return String.valueOf(value);
    }
}

三、请求合并。请求合并在Nginx静态资源加载中也很常见,Nginx使用的是nginx-http-concat扩展模块。可是在Hystric中请求合并会致使延迟增长,因此要求二者启动执行间隔时长足够小,减小等待合并的时间,超过10ms间隔不会自动合并

public class CommandCollapserGetValueForKey extends HystrixCollapser<List<String>, String, Integer> {

    private final Integer key;

    public CommandCollapserGetValueForKey(Integer key) {
        this.key = key;
    }

    @Override
    public Integer getRequestArgument() {
        return key;
    }

    @Override
    protected HystrixCommand<List<String>> createCommand(final Collection<CollapsedRequest<String, Integer>> requests) {
        return new BatchCommand(requests);
    }

    @Override
    protected void mapResponseToRequests(List<String> batchResponse, Collection<CollapsedRequest<String, Integer>> requests) {
        int count = 0;
        for (CollapsedRequest<String, Integer> request : requests) {
            request.setResponse(batchResponse.get(count++));
        }
    }

    private static final class BatchCommand extends HystrixCommand<List<String>> {
        private final Collection<CollapsedRequest<String, Integer>> requests;

        private BatchCommand(Collection<CollapsedRequest<String, Integer>> requests) {
                super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
                    .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueForKey")));
            this.requests = requests;
        }

        @Override
        protected List<String> run() {
            ArrayList<String> response = new ArrayList<String>();
            for (CollapsedRequest<String, Integer> request : requests) {
                // artificial response for each argument received in the batch
                response.add("ValueForKey: " + request.getArgument());
            }
            return response;
        }
    }
}

四、快速失败,不走降级逻辑,直接抛出异常,一般用于非幂等性的写操做。幂等性是指一次和屡次请求某一个资源应该具备一样的反作用,好比bool take(ticket_id, account_id, amount)取钱操做,无论任什么时候候请求失败或超时,调用方均可以重试,固然把参数ticket_id去掉就是非幂等性的了。注意:在Hystrix能够轻松实现重试,只需降级时判断isCircuitBreakerOpen断路器状态可用而后重试便可,不会使问题雪上加霜

public class CommandThatFailsFast extends HystrixCommand<String> {

private final boolean throwException;

public CommandThatFailsFast(boolean throwException) {
    super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
    this.throwException = throwException;
}

@Override
protected String run() {
    if (throwException) {
        throw new RuntimeException("failure from CommandThatFailsFast");
    } else {
        return "success";
    }
}

文章来源:http://www.liangsonghua.me
做者介绍:京东资深工程师-梁松华,长期关注稳定性保障、敏捷开发、JAVA高级、微服务架构

clipboard.png