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調用(沒有網絡開銷)則使用信號量來隔離,更為輕量,開銷更小。