Hystrix线程池、信号量

5.线程池/请求队列/信号量是否占满
如果与命令相关的线程池和请求队列或者信号量已经被占满,那么Hystrix也不会执行命令,而是转接到fallback处理逻辑。
命令名称、分组以及线程池划分
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestGroupKey"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("CommandKey"))
                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("PoolKey")));
我们先调用了withGroupKey来设置命令组名,然后才通过调用andCommandKey来设置命令名。这是因为在Setter的定义中,只有withGroupKey静态函数可以创建Setter的实例,所以GroupKey是每个Setter必须的函数,而CommandKey是一个可选的参数。
通过设置命令组,Hystrix会根据组来组织和统计命令的告警、仪表盘等信息,那么为什么一定要设置命令组呢?因为处理根据足能来实现统计之外,Hystrix命令默认的线程划分也是根据命令分组来实现的。默认情况下,Hystrix会让相同组名的命令使用一个线程池,所以我们需要在创建Hystrix命令时为其指定命令组名来实现默认的线程池划分。
线程池还可以根据HystrixThreadPoolKey来对线程池进行设置。
使用注解的时候这样设置
@HystrixCommand(commandKey="getUserById",groupKey="UserGroup",threadPoolKey="getUserByIdThread")

public class MyCommand extends HystrixCommand<String>{
	private Integer index;
	public MyCommand(Integer index){
		super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestGroup")));
		this.index=index;
	}
	protected String run() throws InterruptedException{
		Thread.sleep(500);
		System.out.println("执行方法,索引:"+index);
		return "success";
	}
	protected String getFallback(){
		System.out.println("执行回退,索引:"+index);
		return "fallback";
	}
}

线程池:
 

public class ThreadMain {

	public static void main(String[] args) throws InterruptedException {
		ConfigurationManager.getConfigInstance().setProperty("hystrix.threadpool.default.coreSize", 3);;
		for(int i=0;i<6;i++){
			MyCommand c=new MyCommand(i);
			c.queue();
		}
		Thread.sleep(5000);
	}

}

信号量:

public class SemaphoreMain {

	public static void main(String[] args) throws InterruptedException {
		ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.strategy", ExecutionIsolationStrategy.SEMAPHORE);
		ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests", 2);
	for(int i=0;i<6;i++){
		final int index=i;
		Thread t=new Thread(){
			public void run(){
				MyCommand c=new MyCommand(index);
				c.queue();
			}
		};
		t.start();
	}
	Thread.sleep(5000);
	}

}
发布了254 篇原创文章 · 获赞 18 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_36594703/article/details/82705331