Hystrix线程池隔离

你们都知道如今web服务都讲究高可用,怎么实现高可用呢,这里边有不少点:
1.nginx多层代理防止单点故障和流量分流
2.不一样服务之间进行隔离,如今流行微服务大概就这个理,按照不一样的业务对系统拆分红独立的web服务,实现进程之间的隔离,当某个服务挂掉的时候,其余的服务继续能够提供对外服务能力
3.多机房集群,一个机房挂掉,其余机房照样能够使用
4.隔离,这里边有不少,好比:静态资源隔离、数据库读写分离、热点资源隔离(秒杀,抢购)、Hystrix隔离nginx

不一样的业务定义不一样的线程池,从而达到当某一个业务出问题的时候,不影响其余的业务,此篇解决的问题与以前写的“Servlet3之线程隔离”相似。web

HystrixCommand线程池隔离

public class GetCourseServiceCommand extends HystrixCommand<String> {

    private CourseService courseService= new CourseService();


    protected GetCourseServiceCommand() {
        super(setter());
    }

   private static Setter setter(){
       //服务分组,配置全局惟一分组名称,默认类名
       HystrixCommandGroupKey groupKey= HystrixCommandGroupKey.Factory.asKey("course");
       //服务标识,配置全局惟一标识名称
       HystrixCommandKey commandKey= HystrixCommandKey.Factory.asKey("getCourse");
       //线程池名称,默认分组名
       HystrixThreadPoolKey threadPoolKey= HystrixThreadPoolKey.Factory.asKey("course-pool");
       //配置线程池
       HystrixThreadPoolProperties.Setter poolProperties= HystrixThreadPoolProperties.Setter()
               .withCoreSize(5)
               .withKeepAliveTimeMinutes(5)//空闲线程的生存时间
               .withMaxQueueSize(1000)//线程池队列最大大小
               .withQueueSizeRejectionThreshold(1000);//这个值影响MaxQueueSize,经过这个值能够动态改变线程池大小
       //配置命令,配置线程池隔离策略
       HystrixCommandProperties.Setter commandProperties= HystrixCommandProperties.Setter()
               .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD);

       return HystrixCommand.Setter.withGroupKey(groupKey)
               .andCommandKey(commandKey)
               .andThreadPoolKey(threadPoolKey)
               .andCommandPropertiesDefaults(commandProperties)
               .andThreadPoolPropertiesDefaults(poolProperties);

   }

    @Override protected String run() throws Exception {
        return courseService.getCourse();
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        GetCourseServiceCommand courseServiceCommand= new GetCourseServiceCommand();
        Future<String> future= courseServiceCommand.queue();
        System.out.println(future.get());
    }

}