程序员

Hystrix线程隔离技术解析-信号量

2017-08-10  本文已影响2041人  新栋BOOK

hystrix的线程隔离技术除了线程池,还有另外一种方式:信号量。

线程池和信号量的区别

《Hystrix线程隔离技术解析-线程池》一文最后,我们谈到了线程池的缺点,当我们依赖的服务是极低延迟的,比如访问内存缓存,就没有必要使用线程池的方式,那样的话开销得不偿失,而是推荐使用信号量这种方式。下面这张图说明了线程池隔离和信号量隔离的主要区别:线程池方式下业务请求线程和执行依赖的服务的线程不是同一个线程;信号量方式下业务请求线程和执行依赖服务的线程是同一个线程

信号量和线程池的区别.png
如何使用信号量来隔离线程

将属性execution.isolation.strategy设置为SEMAPHORE ,象这样 ExecutionIsolationStrategy.SEMAPHORE,则Hystrix使用信号量而不是默认的线程池来做隔离。

public class CommandUsingSemaphoreIsolation extends HystrixCommand<String> {

    private final int id;

    public CommandUsingSemaphoreIsolation(int id) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
                // since we're doing work in the run() method that doesn't involve network traffic
                // and executes very fast with low risk we choose SEMAPHORE isolation
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                        .withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)));
        this.id = id;
    }

    @Override
    protected String run() {
        // a real implementation would retrieve data from in memory data structure
        // or some other similar non-network involved work
        return "ValueFromHashMap_" + id;
    }

}
总结

信号量隔离的方式是限制了总的并发数,每一次请求过来,请求线程和调用依赖服务的线程是同一个线程,那么如果不涉及远程RPC调用(没有网络开销)则使用信号量来隔离,更为轻量,开销更小。

转载请注明出处,并附上链接http://www.jianshu.com/p/af8dc67e5238

参考资料:https://github.com/Netflix/Hystrix/wiki

上一篇 下一篇

猜你喜欢

热点阅读