8 高并发解决方案

首页 / 新闻资讯 / 正文

 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);     } }