8.1 高併發問題分析
8.2 代碼實現
package xx.study.sc.command;
import com.netflix.hystrix.*;
import org.springframework.web.client.RestTemplate;
import xx.study.sc.model.Product;
public class OrderCommand extends HystrixCommand<Product> {
private RestTemplate restTemplate;
private Long id;
public OrderCommand(RestTemplate restTemplate,Long id){
super(setter());
this.restTemplate=restTemplate;
this.id=id;
}
private static Setter setter(){
//服務分組
HystrixCommandGroupKey groupKey=HystrixCommandGroupKey.Factory.asKey("order_product");
//服務標識
HystrixCommandKey commandKey=HystrixCommandKey.Factory.asKey("product");
//線程池名稱
HystrixThreadPoolKey threadPoolKey=HystrixThreadPoolKey.Factory.asKey("order_produt_pool");
/**
* 線程池配置
* withCoreSize :線程池大小
* withKeepAliveTimeMinutes:線程存活時間15s
* withQueueSizeRejectionThreshold:隊列等待的閾值爲100,超過100執行拒絕策略
*/
HystrixThreadPoolProperties.Setter threadPoolProperties=HystrixThreadPoolProperties.Setter().withCoreSize(50).
withKeepAliveTimeMinutes(15).withQueueSizeRejectionThreshold(100);
//命令屬性配置Hystrix開啓超時
HystrixCommandProperties.Setter commandProperties=HystrixCommandProperties.Setter().
//採用線程池隔離
withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
.withExecutionTimeoutEnabled(false);
return Setter.withGroupKey(groupKey).andCommandKey(commandKey).andThreadPoolKey(threadPoolKey)
.andThreadPoolPropertiesDefaults(threadPoolProperties).andCommandPropertiesDefaults(commandProperties);
}
@Override
protected Product run() throws Exception {
return restTemplate.getForObject("http://127.0.0.1:9000/product/buy",Product.class);
}
}