Hystrix线程池隔离

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

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

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

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容