下面列出了怎么用com.netflix.hystrix.HystrixCommandProperties的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void executionIsolationStrategyCanBeChangedAtAnyTime() {
final RandomTenacityKey randomTenacityKey = new RandomTenacityKey(UUID.randomUUID().toString());
assertThat(TenacityObservableCommand.getCommandProperties(randomTenacityKey).executionIsolationStrategy().get())
.isEqualTo(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD);
new TenacityPropertyRegister(ImmutableMap.<TenacityPropertyKey, TenacityConfiguration>of(
randomTenacityKey, new TenacityConfiguration()), new BreakerboxConfiguration()).register();
assertThat(TenacityObservableCommand.getCommandProperties(randomTenacityKey).executionIsolationStrategy().get())
.isEqualTo(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD);
final TenacityConfiguration semaphoreConfiguration = new TenacityConfiguration();
semaphoreConfiguration.setExecutionIsolationThreadTimeoutInMillis(912);
semaphoreConfiguration.setExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE);
new TenacityPropertyRegister(ImmutableMap.<TenacityPropertyKey, TenacityConfiguration>of(
randomTenacityKey, semaphoreConfiguration), new BreakerboxConfiguration()).register();
assertThat(TenacityObservableCommand.getCommandProperties(randomTenacityKey).executionTimeoutInMilliseconds().get())
.isEqualTo(semaphoreConfiguration.getExecutionIsolationThreadTimeoutInMillis());
assertThat(TenacityObservableCommand.getCommandProperties(randomTenacityKey).executionIsolationStrategy().get())
.isEqualTo(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE);
}
private static Setter setter() {
HystrixCommandGroupKey groupkey = HystrixCommandGroupKey.Factory.asKey("rpc");
HystrixCommandKey commandkey = HystrixCommandKey.Factory.asKey("say");
HystrixThreadPoolKey threadpoolkey = HystrixThreadPoolKey.Factory.asKey("hello-1");
HystrixThreadPoolProperties.Setter threadproperties = HystrixThreadPoolProperties.Setter()//
.withCoreSize(20).withKeepAliveTimeMinutes(5).withMaxQueueSize(1000).withQueueSizeRejectionThreshold(100);
HystrixCommandProperties.Setter commandproperty = HystrixCommandProperties.Setter()//
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)//
.withFallbackEnabled(true).withFallbackIsolationSemaphoreMaxConcurrentRequests(100)//
.withExecutionIsolationThreadInterruptOnFutureCancel(true)//
.withExecutionIsolationThreadInterruptOnTimeout(true)//
.withExecutionTimeoutEnabled(true).withExecutionTimeoutInMilliseconds(1000);
return HystrixCommand.Setter.withGroupKey(groupkey).andCommandKey(commandkey)//
.andThreadPoolKey(threadpoolkey).andThreadPoolPropertiesDefaults(threadproperties)//
.andCommandPropertiesDefaults(commandproperty);
}
private static Setter setter() {
HystrixCommandGroupKey groupkey = HystrixCommandGroupKey.Factory.asKey("rpc");
HystrixCommandKey commandkey = HystrixCommandKey.Factory.asKey("say");
HystrixThreadPoolKey threadpoolkey = HystrixThreadPoolKey.Factory.asKey("hello-1");
HystrixThreadPoolProperties.Setter threadproperties = HystrixThreadPoolProperties.Setter()//
.withCoreSize(20).withKeepAliveTimeMinutes(5).withMaxQueueSize(1000).withQueueSizeRejectionThreshold(100);
HystrixCommandProperties.Setter commandproperty = HystrixCommandProperties.Setter()//
.withCircuitBreakerEnabled(true).withCircuitBreakerForceClosed(false)//
.withCircuitBreakerForceOpen(false).withCircuitBreakerErrorThresholdPercentage(50)//
.withCircuitBreakerRequestVolumeThreshold(20)//
.withCircuitBreakerSleepWindowInMilliseconds(5000);
return HystrixCommand.Setter.withGroupKey(groupkey).andCommandKey(commandkey)//
.andThreadPoolKey(threadpoolkey).andThreadPoolPropertiesDefaults(threadproperties)//
.andCommandPropertiesDefaults(commandproperty);
}
public static TenacityConfiguration getTenacityConfiguration(TenacityPropertyKey key) {
final HystrixCommandProperties commandProperties = TenacityCommand.getCommandProperties(key);
final HystrixThreadPoolProperties threadPoolProperties = TenacityCommand.getThreadpoolProperties(key);
return new TenacityConfiguration(
new ThreadPoolConfiguration(
threadPoolProperties.coreSize().get(),
threadPoolProperties.keepAliveTimeMinutes().get(),
threadPoolProperties.maxQueueSize().get(),
threadPoolProperties.queueSizeRejectionThreshold().get(),
threadPoolProperties.metricsRollingStatisticalWindowInMilliseconds().get(),
threadPoolProperties.metricsRollingStatisticalWindowBuckets().get()),
new CircuitBreakerConfiguration(
commandProperties.circuitBreakerRequestVolumeThreshold().get(),
commandProperties.circuitBreakerSleepWindowInMilliseconds().get(),
commandProperties.circuitBreakerErrorThresholdPercentage().get(),
commandProperties.metricsRollingStatisticalWindowInMilliseconds().get(),
commandProperties.metricsRollingStatisticalWindowBuckets().get()),
new SemaphoreConfiguration(
commandProperties.executionIsolationSemaphoreMaxConcurrentRequests().get(),
commandProperties.fallbackIsolationSemaphoreMaxConcurrentRequests().get()),
commandProperties.executionTimeoutInMilliseconds().get(),
commandProperties.executionIsolationStrategy().get());
}
@Test
public void testgetCommandProperties() {
HystrixCommandKey commandKey = Mockito.mock(HystrixCommandKey.class);
Mockito.when(commandKey.name())
.thenReturn("provider.HystrixPropertiesStrategyExtTest.testgetCommandProperties");
HystrixCommandProperties commandPro = HystrixPropertiesStrategyExt.getInstance()
.getCommandProperties(commandKey, HystrixCommandProperties.Setter());
Assert.assertTrue(commandPro.circuitBreakerEnabled().get());
Assert.assertEquals(Integer.valueOf(50), commandPro.circuitBreakerErrorThresholdPercentage().get());
Assert.assertFalse(commandPro.circuitBreakerForceClosed().get());
Assert.assertFalse(commandPro.circuitBreakerForceOpen().get());
Assert.assertEquals(Integer.valueOf(20), commandPro.circuitBreakerRequestVolumeThreshold().get());
Assert.assertEquals(Integer.valueOf(15000), commandPro.circuitBreakerSleepWindowInMilliseconds().get());
Assert.assertEquals(Integer.valueOf(1000), commandPro.executionIsolationSemaphoreMaxConcurrentRequests().get());
Assert.assertTrue(commandPro.executionIsolationThreadInterruptOnTimeout().get());
Assert.assertEquals(null, commandPro.executionIsolationThreadPoolKeyOverride().get());
Assert.assertEquals(Integer.valueOf(30000), commandPro.executionTimeoutInMilliseconds().get());
Assert.assertFalse(commandPro.executionTimeoutEnabled().get());
Assert.assertEquals(Integer.valueOf(10), commandPro.fallbackIsolationSemaphoreMaxConcurrentRequests().get());
Assert.assertTrue(commandPro.fallbackEnabled().get());
Assert.assertEquals(Integer.valueOf(100), commandPro.metricsRollingPercentileBucketSize().get());
Assert.assertFalse(commandPro.metricsRollingPercentileEnabled().get());
}
@Test
public void testResumeWithFallbackProvider() {
Invocation invocation = Mockito.mock(Invocation.class);
Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class));
Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1");
HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
.withRequestCacheEnabled(true)
.withRequestLogEnabled(false);
BizkeeperCommand bizkeeperCommand = new ProviderBizkeeperCommand("groupname", invocation,
HystrixObservableCommand.Setter
.withGroupKey(CommandKey.toHystrixCommandGroupKey("groupname", invocation))
.andCommandKey(CommandKey.toHystrixCommandKey("groupname", invocation))
.andCommandPropertiesDefaults(setter));
Observable<Response> observe = bizkeeperCommand.resumeWithFallback();
Assert.assertNotNull(observe);
}
@Test
public void testConstructProvider() {
Invocation invocation = Mockito.mock(Invocation.class);
Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class));
Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1");
HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
.withRequestCacheEnabled(true)
.withRequestLogEnabled(false);
BizkeeperCommand bizkeeperCommand = new ProviderBizkeeperCommand("groupname", invocation,
HystrixObservableCommand.Setter
.withGroupKey(CommandKey.toHystrixCommandGroupKey("groupname", invocation))
.andCommandKey(CommandKey.toHystrixCommandKey("groupname", invocation))
.andCommandPropertiesDefaults(setter));
Observable<Response> response = bizkeeperCommand.construct();
Assert.assertNotNull(response);
}
@Test
public void testGetCacheKeyWithContextInitializedProvider() {
Invocation invocation = Mockito.mock(Invocation.class);
Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class));
Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1");
HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
.withRequestCacheEnabled(true)
.withRequestLogEnabled(false);
BizkeeperCommand bizkeeperCommand = new ProviderBizkeeperCommand("groupname", invocation,
HystrixObservableCommand.Setter
.withGroupKey(CommandKey.toHystrixCommandGroupKey("groupname", invocation))
.andCommandKey(CommandKey.toHystrixCommandKey("groupname", invocation))
.andCommandPropertiesDefaults(setter));
HystrixRequestContext.initializeContext();
String cacheKey = bizkeeperCommand.getCacheKey();
Assert.assertNotNull(cacheKey);
}
public static Optional<CircuitBreaker> usingHystrix(TenacityPropertyKey id) {
final HystrixCircuitBreaker circuitBreaker = TenacityCommand.getCircuitBreaker(id);
if (circuitBreaker == null) {
return Optional.empty();
}
final HystrixCommandProperties commandProperties = TenacityCommand.getCommandProperties(id);
if (commandProperties.circuitBreakerForceOpen().get()) {
return Optional.of(CircuitBreaker.forcedOpen(id));
} else if (commandProperties.circuitBreakerForceClosed().get()) {
return Optional.of(CircuitBreaker.forcedClosed(id));
} else if (circuitBreaker.allowRequest()) {
return Optional.of(CircuitBreaker.closed(id));
} else {
return Optional.of(CircuitBreaker.open(id));
}
}
@Test
public void differentContextCanHaveDifferentSettingsForSameApi() throws Throwable {
astrixConfigurer.set(AstrixBeanSettings.TIMEOUT, AstrixBeanKey.create(Ping.class), 100);
TestAstrixConfigurer astrixConfigurer2 = new TestAstrixConfigurer();
astrixConfigurer2.set(AstrixBeanSettings.TIMEOUT, AstrixBeanKey.create(Ping.class), 200);
astrixConfigurer2.enableFaultTolerance(true);
astrixConfigurer2.registerApiProvider(PingApi.class);
AstrixContext astrixContext2 = autoClosables.add(astrixConfigurer2.configure());
astrixContext.getBean(Ping.class).ping("foo");
HystrixFaultToleranceFactory hystrixFaultTolerance = getFaultTolerance(astrixContext);
HystrixFaultToleranceFactory hystrixFaultTolerance2 = getFaultTolerance(astrixContext2);
HystrixCommandProperties pingCommandPropertiesContext1 = getHystrixCommandProperties(hystrixFaultTolerance, Ping.class);
HystrixCommandProperties pingCommandPropertiesContext2 = getHystrixCommandProperties(hystrixFaultTolerance2, Ping.class);
assertEquals(100, pingCommandPropertiesContext1.executionTimeoutInMilliseconds().get().intValue());
assertEquals(200, pingCommandPropertiesContext2.executionTimeoutInMilliseconds().get().intValue());
}
@Test
public void readsDefaultBeanSettingsFromBeanConfiguration() throws Throwable {
astrixConfigurer.set(AstrixBeanSettings.CORE_SIZE, AstrixBeanKey.create(Ping.class), 4);
astrixConfigurer.set(AstrixBeanSettings.QUEUE_SIZE_REJECTION_THRESHOLD, AstrixBeanKey.create(Ping.class), 6);
astrixConfigurer.set(AstrixBeanSettings.TIMEOUT, AstrixBeanKey.create(Ping.class), 100);
astrixConfigurer.set(AstrixBeanSettings.MAX_CONCURRENT_REQUESTS, AstrixBeanKey.create(Ping.class), 21);
astrixContext.getBean(Ping.class).ping("foo");
HystrixFaultToleranceFactory hystrixFaultTolerance = getFaultTolerance(astrixContext);
HystrixCommandProperties pingCommandProperties = getHystrixCommandProperties(hystrixFaultTolerance, Ping.class);
HystrixThreadPoolProperties pingThreadPoolProperties = getThreadPoolProperties(hystrixFaultTolerance, Ping.class);
assertEquals(100, pingCommandProperties.executionTimeoutInMilliseconds().get().intValue());
assertEquals(21, pingCommandProperties.executionIsolationSemaphoreMaxConcurrentRequests().get().intValue());
assertEquals(4, pingThreadPoolProperties.coreSize().get().intValue());
assertEquals(6, pingThreadPoolProperties.queueSizeRejectionThreshold().get().intValue());
}
@Test
public void shouldIncrementCounterHistogramForExecuteButNotLatencyOnCancelledCommand() {
// given
HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.defaultSetter();
TestHystrixCommand command = new TestHystrixCommand("cancelledCommand",
commandProperties).willWait(10);
command.queue().cancel(true);
// then
assertThat(CollectorRegistry.defaultRegistry.getSampleValue(
"exampleapp_hystrix_command_latency_execute_seconds_count",
new String[]{"command_group", "command_name"},
new String[]{"group_cancelledCommand", "command_cancelledCommand"}
))
.describedAs("counter of all executions in the histogram")
.isEqualTo(1);
assertThat(CollectorRegistry.defaultRegistry.getSampleValue(
"exampleapp_hystrix_command_latency_total_seconds_count",
new String[]{"command_group", "command_name"},
new String[]{"group_cancelledCommand", "command_cancelledCommand"}
))
.describedAs("counter of all executions in the histogram")
.isEqualTo(0);
}
public MessageInvokeCommandForThreadIsolation(String consumerGroupName, ConsumerQueueDto pre, List<MessageDto> dtos,
ISubscriber iSubscriber) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(consumerGroupName))
.andCommandKey(HystrixCommandKey.Factory.asKey(consumerGroupName + "." + pre.getOriginTopicName()))
.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(consumerGroupName + "." + pre.getQueueId()))
.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(pre.getThreadSize()))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
// .withExecutionTimeoutInMilliseconds(pre.getTimeout() * 1000)
.withExecutionTimeoutEnabled(true)
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
.withCircuitBreakerEnabled(false)));
this.iSubscriber1 = iSubscriber;
this.pre1 = pre;
this.dtos = dtos;
}
@Test
public void getTenacityConfiguration() {
assertThat(TENACITYCLIENT.getTenacityConfiguration(ROOT, TenacityClientPropertyKey.CLIENT_KEY))
.contains(CLIENT_KEY_CONFIGURATION);
assertThat(TENACITYCLIENT.getTenacityConfiguration(ROOT, NonExistentKey.NOPE))
.contains(new TenacityConfiguration(
new ThreadPoolConfiguration(),
new CircuitBreakerConfiguration(),
new SemaphoreConfiguration(),
1000,
HystrixCommandProperties.ExecutionIsolationStrategy.THREAD));
}
protected NIWSCommand(LoadBalancingHttpClient<ByteBuf, ByteBuf> httpClient, HttpClientRequest<ByteBuf> req,
HystrixCommandKey key) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("prana")).andCommandKey(key).
andCommandPropertiesDefaults(HystrixCommandProperties.Setter().
withExecutionIsolationThreadTimeoutInMilliseconds(10000).
withRequestCacheEnabled(false).
withExecutionIsolationSemaphoreMaxConcurrentRequests(1000).
withCircuitBreakerEnabled(false)));
this.httpClient = httpClient;
this.req = req;
}
@Bean
public Customizer<ReactiveHystrixCircuitBreakerFactory> defaultConfig() {
return factory -> factory.configureDefault(id -> {
return HystrixObservableCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(id))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionTimeoutInMilliseconds(3000));
});
}
public MockServiceCommand(long id, int numItems, int itemSize, int delay) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("MiddleTier"))
.andCommandKey(HystrixCommandKey.Factory.asKey("MiddleTier"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionIsolationSemaphoreMaxConcurrentRequests(5)
.withExecutionTimeoutInMilliseconds(200))); // change this timeout to <= 80 to see fallbacks
this.id = id;
this.numItems = numItems;
this.itemSize = itemSize;
this.delay = delay;
}
protected FwHystrixCommondSemaphore(String name) {
super(HystrixCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("myGroup"))
.andCommandPropertiesDefaults(
HystrixCommandProperties.Setter().withExecutionIsolationStrategy(
HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE
)
));
this.name = name;
}
protected FwHystrixCommondThread(String name) {
super(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("myGroup"))
.andCommandPropertiesDefaults(
HystrixCommandProperties.Setter().withExecutionIsolationStrategy(
HystrixCommandProperties.ExecutionIsolationStrategy.THREAD
)
).andThreadPoolPropertiesDefaults(
HystrixThreadPoolProperties.Setter()
.withCoreSize(3)
));
this.name = name;
}
private CloudReactiveFeign.SetterFactory getSetterFactoryWithTimeoutDisabled() {
return (target, methodMetadata) -> {
String groupKey = target.name();
HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey(methodMetadata.configKey());
return HystrixObservableCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
.andCommandKey(commandKey)
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionTimeoutEnabled(false)
);
};
}
public RibbonRequestCommandForSemaphoreIsolation(AbstractLoadBalancerAwareClient client,HttpRequest request, String serviceName, String commandGroup,
String commandKey) {
super(client,request, serviceName, commandGroup, commandKey,
Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(commandGroup))
.andCommandKey(HystrixCommandKey.Factory.asKey(commandKey))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionIsolationStrategy(
HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)));
}
public ZuulRequestCommandForSemaphoreIsolation(HttpClient httpclient, HttpUriRequest httpUriRequest, HttpContext httpContext, String commandGroup, String commandKey) {
super(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey(commandGroup))
.andCommandKey(HystrixCommandKey.Factory.asKey(commandKey))
.andCommandPropertiesDefaults(
// we want to default to semaphore-isolation since this wraps
// 2 others commands that are already thread isolated
HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)
));
this.httpclient = httpclient;
this.httpUriRequest = httpUriRequest;
this.httpContext = httpContext;
}
protected AbstractCommand() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("spring2go_zuul"))
.andCommandPropertiesDefaults(
HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)
.withExecutionIsolationSemaphoreMaxConcurrentRequests(5))
);
}
public HelloCommand(String name) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ThreadPoolTestGroup"))
.andCommandKey(HystrixCommandKey.Factory.asKey("testCommandKey"))
.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(name))
.andCommandPropertiesDefaults(
HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(20000))
.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withMaxQueueSize(5) // 配置队列大小
.withCoreSize(2) // 配置线程池里的线程数
));
}
@Test
public void configurationExist() {
final TenacityConfiguration tenacityConfiguration = new TenacityConfiguration();
tenacityConfiguration.setExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD);
assertThat(CLIENT.getTenacityConfiguration(URI_ROOT, ServletKeys.KEY_ONE))
.contains(tenacityConfiguration);
response = tenacityConfiguration(ServletKeys.KEY_ONE);
assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
}
private static Setter setter() {
HystrixCommandGroupKey groupkey = HystrixCommandGroupKey.Factory.asKey("rpc");
HystrixCommandKey commandkey = HystrixCommandKey.Factory.asKey("say");
HystrixThreadPoolKey threadpoolkey = HystrixThreadPoolKey.Factory.asKey("hello-1");
HystrixThreadPoolProperties.Setter threadproperties = HystrixThreadPoolProperties.Setter()//
.withCoreSize(1).withKeepAliveTimeMinutes(1).withMaxQueueSize(1000).withQueueSizeRejectionThreshold(2);
HystrixCommandProperties.Setter commandproperty = HystrixCommandProperties.Setter()//
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD);
return HystrixCommand.Setter.withGroupKey(groupkey).andCommandKey(commandkey)//
.andThreadPoolKey(threadpoolkey).andThreadPoolPropertiesDefaults(threadproperties)//
.andCommandPropertiesDefaults(commandproperty);
}
public TakinHystrixCommand(RemotingContext context) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(context.getProtocol().getDefineClass().getName()))//
.andCommandKey(HystrixCommandKey.Factory.asKey(//
String.format("%s_%d", context.getProtocol().getMethod(), context.getProtocol().getArgs() == null ? 0 : context.getProtocol().getArgs().length)))//
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()//
.withCircuitBreakerRequestVolumeThreshold(20)//10秒钟内至少19此请求失败,熔断器才发挥起作用
.withCircuitBreakerSleepWindowInMilliseconds(30000)//熔断器中断请求30秒后会进入半打开状态,放部分流量过去重试
.withCircuitBreakerErrorThresholdPercentage(50)//错误率达到50开启熔断保护
.withExecutionTimeoutEnabled(false))//使用dubbo的超时,禁用这里的超时
.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(DEFAULT_THREADPOOL_CORE_SIZE)));//线程池为30
this.context = context;
logger.info("use TakinHystrixCommand");
}
private static Setter setter() {
HystrixCommandGroupKey groupkey = HystrixCommandGroupKey.Factory.asKey("rpc");
HystrixCommandKey commandkey = HystrixCommandKey.Factory.asKey("say");
HystrixThreadPoolKey threadpoolkey = HystrixThreadPoolKey.Factory.asKey("hello-1");
HystrixThreadPoolProperties.Setter threadproperties = HystrixThreadPoolProperties.Setter()//
.withCoreSize(20).withKeepAliveTimeMinutes(5).withMaxQueueSize(1000).withQueueSizeRejectionThreshold(100);
HystrixCommandProperties.Setter commandproperty = HystrixCommandProperties.Setter()//
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)//
.withExecutionIsolationSemaphoreMaxConcurrentRequests(10);
return HystrixCommand.Setter.withGroupKey(groupkey).andCommandKey(commandkey)//
.andThreadPoolKey(threadpoolkey).andThreadPoolPropertiesDefaults(threadproperties)//
.andCommandPropertiesDefaults(commandproperty);
}
@Override
public HystrixCommandProperties getCommandProperties(HystrixCommandKey commandKey, Setter builder) {
HystrixCommandProperties commandProperties = commandPropertiesMap.get(commandKey.name());
if (commandProperties == null) {
commandProperties = new HystrixCommandPropertiesExt(commandKey, builder);
commandPropertiesMap.putIfAbsent(commandKey.name(), commandProperties);
}
return commandProperties;
}
@Test
public void executionIsolationStrategyCanByChangedByRegister() {
final RandomTenacityKey randomTenacityKey = new RandomTenacityKey(UUID.randomUUID().toString());
final TenacityConfiguration semaphoreConfiguration = new TenacityConfiguration();
semaphoreConfiguration.setExecutionIsolationThreadTimeoutInMillis(912);
semaphoreConfiguration.setExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE);
new TenacityPropertyRegister(ImmutableMap.<TenacityPropertyKey, TenacityConfiguration>of(
randomTenacityKey, semaphoreConfiguration), new BreakerboxConfiguration()).register();
assertThat(TenacityObservableCommand.getCommandProperties(randomTenacityKey).executionTimeoutInMilliseconds().get())
.isEqualTo(semaphoreConfiguration.getExecutionIsolationThreadTimeoutInMillis());
assertThat(TenacityObservableCommand.getCommandProperties(randomTenacityKey).executionIsolationStrategy().get())
.isEqualTo(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE);
}