com.netflix.hystrix.HystrixCommandKey Java Examples

The following examples show how to use com.netflix.hystrix.HystrixCommandKey. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CircutBreakerEventNotifier.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void markEvent(HystrixEventType eventType, HystrixCommandKey key) {
  String keyName = key.name();
  AtomicBoolean flag = circuitFlag.computeIfAbsent(keyName, k -> new AtomicBoolean());
  switch (eventType) {
    case SHORT_CIRCUITED:
      if (flag.compareAndSet(false, true)) {
        eventBus.post(new CircutBreakerEvent(key, Type.OPEN));
      }
      break;

    case SUCCESS:
      if (flag.compareAndSet(true, false)) {
        eventBus.post(new CircutBreakerEvent(key, Type.CLOSE));
      }
      break;

    default:
      break;
  }
}
 
Example #2
Source File: HippoCommand.java    From hippo with Apache License 2.0 6 votes vote down vote up
public HippoCommand(HippoRequest hippoRequest, int timeOut, int retryTimes,
    boolean isCircuitBreaker, int semaphoreMaxConcurrentRequests, Class<?> downgradeStrategy,
    boolean fallbackEnabled) throws InstantiationException, IllegalAccessException {

  // 默认隔离策略是线程 也可以是信号量,现在采用的是信号量的模式
  // 信号量隔离是个限流的策略
  // 因为是自己实现的超时机制,所以关闭hystrix的超时机制
  super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(hippoRequest.getServiceName()))
      .andCommandKey(HystrixCommandKey.Factory.asKey(hippoRequest.getClassName()))
      .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
          .withExecutionIsolationStrategy(
              HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)
          .withExecutionIsolationSemaphoreMaxConcurrentRequests(semaphoreMaxConcurrentRequests)
          .withFallbackEnabled(fallbackEnabled).withCircuitBreakerEnabled(isCircuitBreaker)
          .withExecutionTimeoutEnabled(false)));

  this.hippoRequest = hippoRequest;
  this.timeout = timeOut;
  this.retryTimes = retryTimes;

  if (fallbackEnabled) {
    init(downgradeStrategy);
  }
}
 
Example #3
Source File: MultiEventNotifierDispatcher.java    From astrix with Apache License 2.0 6 votes vote down vote up
@Override
public void markEvent(HystrixEventType eventType, HystrixCommandKey key) {
    if (MultiConfigId.hasMultiSourceId(key)) {
        strategies.get(MultiConfigId.readFrom(key))
                  .markEvent(eventType, MultiConfigId.decode(key));
    }
    else {
        underlying()
                .map(notifier -> {
                    notifier.markEvent(eventType, key);
                    return null;
                })
                .orElseGet(() -> {
                    super.markEvent(eventType, key);
                    return null;
                });
    }
}
 
Example #4
Source File: MultiEventNotifierDispatcher.java    From astrix with Apache License 2.0 6 votes vote down vote up
@Override
public void markCommandExecution(HystrixCommandKey key, ExecutionIsolationStrategy isolationStrategy, int duration, List<HystrixEventType> eventsDuringExecution) {
    if (MultiConfigId.hasMultiSourceId(key)) {
        strategies.get(MultiConfigId.readFrom(key))
                  .markCommandExecution(MultiConfigId.decode(key), isolationStrategy, duration, eventsDuringExecution);
    }
    else {
        underlying()
                .map(notifier -> {
                    notifier.markCommandExecution(key, isolationStrategy, duration, eventsDuringExecution);
                    return null;
                })
                .orElseGet(() -> {
                    super.markCommandExecution(key, isolationStrategy, duration, eventsDuringExecution);
                    return null;
                });
    }
}
 
Example #5
Source File: HystrixKafkaCircuitBreaker.java    From nakadi with MIT License 6 votes vote down vote up
public HystrixKafkaCircuitBreaker(final String brokerId) {
    commandKey = HystrixCommandKey.Factory.asKey(brokerId);
    commandProperties = HystrixPropertiesFactory.getCommandProperties(commandKey, null);
    threadPoolKey = HystrixThreadPoolKey.Factory.asKey(brokerId);
    hystrixCommandMetrics = HystrixCommandMetrics.getInstance(
            commandKey,
            HYSTRIX_CMD_GROUP_KEY,
            threadPoolKey,
            commandProperties);
    circuitBreaker = HystrixCircuitBreaker.Factory.getInstance(
            commandKey,
            HYSTRIX_CMD_GROUP_KEY,
            commandProperties,
            hystrixCommandMetrics);
    concurrentExecutionCount = new AtomicInteger();
}
 
Example #6
Source File: DefaultSetterFactory.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public HystrixCommand.Setter createSetter(FilterInvoker invoker, SofaRequest request) {
    Method clientMethod = request.getMethod();
    if (!SETTER_CACHE.containsKey(clientMethod)) {
        synchronized (DefaultSetterFactory.class) {
            if (!SETTER_CACHE.containsKey(clientMethod)) {
                String interfaceId = invoker.getConfig().getInterfaceId();
                String commandKey = generateCommandKey(interfaceId, request.getMethod());
                HystrixCommand.Setter setter = HystrixCommand.Setter
                    .withGroupKey(HystrixCommandGroupKey.Factory.asKey(interfaceId))
                    .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey));
                SETTER_CACHE.put(clientMethod, setter);
            }
        }
    }
    return SETTER_CACHE.get(clientMethod);
}
 
Example #7
Source File: HelloDegrade.java    From TakinRPC with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #8
Source File: GrpcHystrixCommand.java    From saluki with Apache License 2.0 6 votes vote down vote up
public GrpcHystrixCommand(String serviceName, String methodName, Boolean isEnabledFallBack) {
  super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(serviceName))//
      .andCommandKey(HystrixCommandKey.Factory.asKey(serviceName + ":" + methodName))//
      .andCommandPropertiesDefaults(
          HystrixCommandProperties.Setter().withCircuitBreakerRequestVolumeThreshold(20)// 10秒钟内至少19此请求失败,熔断器才发挥起作用
              .withCircuitBreakerSleepWindowInMilliseconds(30000)// 熔断器中断请求30秒后会进入半打开状态,放部分流量过去重试
              .withCircuitBreakerErrorThresholdPercentage(50)// 错误率达到50开启熔断保护
              .withExecutionTimeoutEnabled(false)// 禁用这里的超时
              .withFallbackEnabled(isEnabledFallBack))//
      .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(100)
          .withAllowMaximumSizeToDivergeFromCoreSize(true).withMaximumSize(Integer.MAX_VALUE)));
  this.serviceName = serviceName;
  this.methodName = methodName;
  this.start = System.currentTimeMillis();
  this.rpcContext = new ImmutableTriple<Map<String, String>, Map<String, Object>, Set<Class>>(
      RpcContext.getContext().getAttachments(), RpcContext.getContext().get(),
      RpcContext.getContext().getHoldenGroups());
  RpcContext.removeContext();
}
 
Example #9
Source File: TestHystrixPropertiesStrategyExt.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #10
Source File: TestHystrixPropertiesStrategyExt.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCommandPropertiesCacheKey() {

  assertNotNull(HystrixPropertiesStrategyExt.getInstance());

  HystrixPropertiesStrategyExt hps = HystrixPropertiesStrategyExt.getInstance();
  HystrixCommandKey commandKey = Mockito.mock(HystrixCommandKey.class);

  Invocation invocation = Mockito.mock(Invocation.class);
  Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class));
  Mockito.when(invocation.getOperationMeta().getMicroserviceName()).thenReturn("testqualify");

  HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
      .withRequestCacheEnabled(true)
      .withRequestLogEnabled(false)
      .withFallbackIsolationSemaphoreMaxConcurrentRequests(
          Configuration.INSTANCE.getFallbackMaxConcurrentRequests("groupname",
              "testing",
              invocation.getOperationMeta().getMicroserviceQualifiedName()));

  String str1 = hps.getCommandPropertiesCacheKey(commandKey, setter);
  Assert.assertNull(str1);
}
 
Example #11
Source File: HystrixFaulttoleranceIntegrationTest.java    From astrix with Apache License 2.0 5 votes vote down vote up
private void initMetrics(Ping ping) throws InterruptedException {
	// Black hystrix magic here :(
	try {
		ping.ping("foo");
	} catch (Exception e) {
	}
	HystrixFaultToleranceFactory faultTolerance = (HystrixFaultToleranceFactory) AstrixApplicationContext.class.cast(this.context).getInstance(BeanFaultToleranceFactorySpi.class);
	HystrixCommandKey key = faultTolerance.getCommandKey(AstrixBeanKey.create(Ping.class));
	
	HystrixCommandMetrics.getInstance(key).getCumulativeCount(HystrixEventType.SUCCESS);
}
 
Example #12
Source File: CustommerCommand.java    From resilient-transport-service with Apache License 2.0 5 votes vote down vote up
public CustommerCommand(Long custommerId, RestTemplate restTemplate, boolean secondTry) {
    super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("CustomerServiceClientGroup"))
        .andCommandKey(HystrixCommandKey.Factory.asKey("CustomerServiceClient")));
    this.custommerId = custommerId;
    this.restTemplate = restTemplate;

    this.secondTry = secondTry;
}
 
Example #13
Source File: HystrixObservableCommandFacadeTest.java    From astrix with Apache License 2.0 5 votes vote down vote up
private void initMetrics(Ping ping) throws InterruptedException {
	// Black hystrix magic here :(
	try {
		ping.ping();
	} catch (Exception e) {
	}
	HystrixFaultToleranceFactory faultTolerance = (HystrixFaultToleranceFactory) AstrixApplicationContext.class.cast(this.context).getInstance(BeanFaultToleranceFactorySpi.class);
	HystrixCommandKey key = faultTolerance.getCommandKey(AstrixBeanKey.create(Ping.class));
	
	HystrixCommandMetrics.getInstance(key).getCumulativeCount(HystrixEventType.SUCCESS);
}
 
Example #14
Source File: AstrixCommandProperties.java    From astrix with Apache License 2.0 5 votes vote down vote up
AstrixCommandProperties(BeanConfiguration beanConfiguration, HystrixCommandKey key, com.netflix.hystrix.HystrixCommandProperties.Setter builder) {
	super(key, builder);
	this.isolationStrategy = builder.getExecutionIsolationStrategy();
	
	// We create all these property adaptors here as each and every one results in creation of several temporary String objects.
	// The alternative to this, to create the adaptors at call-time in the various methods of this class, results in large amounts
	// of temporary objects and thus heavy GC load in systems with many astrix calls.
	this.executionTimeoutInMilliseconds = new DynamicPropertyAdapter<>(beanConfiguration.get(AstrixBeanSettings.TIMEOUT));
	this.circuitBreakerEnabled = new DynamicPropertyAdapter<>(beanConfiguration.get(new BooleanBeanSetting("faultTolerance.circuitBreakerEnabled", true)));
	this.circuitBreakerErrorThresholdPercentage = new DynamicPropertyAdapter<>(beanConfiguration.get(new IntBeanSetting("faultTolerance.circuitBreakerErrorThresholdPercentage", 50)));
	this.circuitBreakerForceClosed = new DynamicPropertyAdapter<>(beanConfiguration.get(new BooleanBeanSetting("faultTolerance.circuitBreakerForceClosed", false)));
	this.circuitBreakerForceOpen = new DynamicPropertyAdapter<>(beanConfiguration.get(new BooleanBeanSetting("faultTolerance.circuitBreakerForceOpen", false)));
	this.circuitBreakerRequestVolumeThreshold = new DynamicPropertyAdapter<>(beanConfiguration.get(new IntBeanSetting("faultTolerance.circuitBreakerRequestVolumeThreshold", 20)));
	this.circuitBreakerSleepWindowInMilliseconds = new DynamicPropertyAdapter<>(beanConfiguration.get(new IntBeanSetting("faultTolerance.circuitBreakerSleepWindowInMilliseconds", 5000)));
	this.executionIsolationSemaphoreMaxConcurrentRequests = new DynamicPropertyAdapter<>(beanConfiguration.get(AstrixBeanSettings.MAX_CONCURRENT_REQUESTS));
	this.executionIsolationThreadInterruptOnTimeout = new DynamicPropertyAdapter<>(beanConfiguration.get(new BooleanBeanSetting("faultTolerance.executionIsolationThreadInterruptOnTimeout", true)));
	this.executionIsolationThreadPoolKeyOverride =  new DynamicPropertyAdapter<>(beanConfiguration.get(new StringBeanSetting("faultTolerance.executionIsolationThreadPoolKeyOverride", null)));
	this.executionTimeoutEnabled = new DynamicPropertyAdapter<>(beanConfiguration.get(new BooleanBeanSetting("faultTolerance.executionTimeoutEnabled", true)));
	this.fallbackEnabled = new DynamicPropertyAdapter<>(beanConfiguration.get(new BooleanBeanSetting("faultTolerance.fallbackEnabled", true)));
	this.metricsHealthSnapshotIntervalInMilliseconds = new DynamicPropertyAdapter<>(beanConfiguration.get(new IntBeanSetting("faultTolerance.metricsHealthSnapshotIntervalInMilliseconds", 500)));
	this.metricsRollingPercentileBucketSize = new DynamicPropertyAdapter<>(beanConfiguration.get(new IntBeanSetting("faultTolerance.metricsRollingPercentileBucketSize", 100)));
	this.metricsRollingPercentileEnabled = new DynamicPropertyAdapter<>(beanConfiguration.get(new BooleanBeanSetting("faultTolerance.metricsRollingPercentileEnabled", true)));
	this.metricsRollingPercentileWindowBuckets = new DynamicPropertyAdapter<>(beanConfiguration.get(new IntBeanSetting("faultTolerance.metricsRollingPercentileWindowBuckets", 6)));
	this.metricsRollingPercentileWindowInMilliseconds = new DynamicPropertyAdapter<>(beanConfiguration.get(new IntBeanSetting("faultTolerance.metricsRollingPercentileWindowInMilliseconds", 60_000)));
	this.metricsRollingStatisticalWindowBuckets = new DynamicPropertyAdapter<>(beanConfiguration.get(new IntBeanSetting("faultTolerance.metricsRollingStatisticalWindowBuckets", 10)));
	this.metricsRollingStatisticalWindowInMilliseconds = new DynamicPropertyAdapter<>(beanConfiguration.get(new IntBeanSetting("faultTolerance.metricsRollingStatisticalWindowInMilliseconds", 10_000)));
	this.requestCacheEnabled = new DynamicPropertyAdapter<>(beanConfiguration.get(new BooleanBeanSetting("faultTolerance.requestCacheEnabled", false)));
	this.requestLogEnabled = new DynamicPropertyAdapter<>(beanConfiguration.get(new BooleanBeanSetting("faultTolerance.requestLogEnabled", false)));
}
 
Example #15
Source File: ArqHystrixTest.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfigurationThroughArchaius() {
    HystrixPropertiesStrategy strategy = HystrixPlugins.getInstance().getPropertiesStrategy();

    HystrixCommandProperties defaultProps = strategy.getCommandProperties(HystrixCommandKey.Factory.asKey("default"), HystrixCommandProperties.Setter());

    assertFalse( defaultProps.circuitBreakerEnabled().get());
    assertEquals(77, (int) defaultProps.circuitBreakerErrorThresholdPercentage().get());

    HystrixCommandProperties gooberProps = strategy.getCommandProperties(HystrixCommandKey.Factory.asKey("goober"), HystrixCommandProperties.Setter());
    assertTrue( gooberProps.circuitBreakerEnabled().get());
    assertEquals(44, (int) gooberProps.circuitBreakerErrorThresholdPercentage().get());
}
 
Example #16
Source File: MultiPropertiesStrategyDispatcherTest.java    From astrix with Apache License 2.0 5 votes vote down vote up
@Test
public void decodesIncomingCommandKeys() throws Exception {
	HystrixPropertiesStrategy mock = Mockito.mock(HystrixPropertiesStrategy.class);
	MultiConfigId configId = MultiConfigId.create("t1");
	
	dispatcher.register(configId.toString(), mock);
	dispatcher.getCommandProperties(configId.createCommandKey("com.avanza.test.TestApi.TestService"), defaultCommandSetter);
	
	Mockito.verify(mock).getCommandProperties(HystrixCommandKey.Factory.asKey("com.avanza.test.TestApi.TestService"), defaultCommandSetter);
}
 
Example #17
Source File: HystrixCommandInterceptor.java    From micro-service with MIT License 5 votes vote down vote up
private HystrixCommand.Setter configHystrixCommand(String className, String methodName) {
	return HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(className + "Group"))
			.andCommandKey(HystrixCommandKey.Factory.asKey(className + "." + methodName))
			.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(className + "ThreadPool"))
			.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
			.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD))
			.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(10));
}
 
Example #18
Source File: MultiConfigIdTest.java    From astrix with Apache License 2.0 5 votes vote down vote up
@Test
public void hasMultiSourceId() throws Exception {
	String name = "com.avanza.test.TestServiceApi.TestService";
	assertTrue(MultiConfigId.hasMultiSourceId(MultiConfigId.create("t-T1").createCommandKey(name)));
	assertTrue(MultiConfigId.hasMultiSourceId(MultiConfigId.create("t-T1").createCollapserKey(name)));
	assertTrue(MultiConfigId.hasMultiSourceId(MultiConfigId.create("t-T1").createThreadPoolKey(name)));
	
	assertFalse(MultiConfigId.hasMultiSourceId(HystrixCommandKey.Factory.asKey(name)));
	assertFalse(MultiConfigId.hasMultiSourceId(HystrixCollapserKey.Factory.asKey(name)));
	assertFalse(MultiConfigId.hasMultiSourceId(HystrixThreadPoolKey.Factory.asKey(name)));
}
 
Example #19
Source File: HystrixBuilder.java    From bird-java with MIT License 5 votes vote down vote up
/**
 * this is build HystrixObservableCommand.Setter.
 *
 * @param hystrixHandle {@linkplain HystrixHandle}
 * @return {@linkplain HystrixObservableCommand.Setter}
 */
public static HystrixObservableCommand.Setter build(final HystrixHandle hystrixHandle) {

    if (hystrixHandle.getMaxConcurrentRequests() == 0) {
        hystrixHandle.setMaxConcurrentRequests(GatewayConstant.MAX_CONCURRENT_REQUESTS);
    }
    if (hystrixHandle.getErrorThresholdPercentage() == 0) {
        hystrixHandle.setErrorThresholdPercentage(GatewayConstant.ERROR_THRESHOLD_PERCENTAGE);
    }
    if (hystrixHandle.getRequestVolumeThreshold() == 0) {
        hystrixHandle.setRequestVolumeThreshold(GatewayConstant.REQUEST_VOLUME_THRESHOLD);
    }
    if (hystrixHandle.getSleepWindowInMilliseconds() == 0) {
        hystrixHandle.setSleepWindowInMilliseconds(GatewayConstant.SLEEP_WINDOW_INMILLISECONDS);
    }

    HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey(hystrixHandle.getGroupKey());

    HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey(hystrixHandle.getCommandKey());

    final HystrixCommandProperties.Setter propertiesSetter =
            HystrixCommandProperties.Setter()
                    .withExecutionTimeoutInMilliseconds(hystrixHandle.getTimeout())
                    .withCircuitBreakerEnabled(true)
                    .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)
                    .withExecutionIsolationSemaphoreMaxConcurrentRequests(hystrixHandle.getMaxConcurrentRequests())
                    .withCircuitBreakerErrorThresholdPercentage(hystrixHandle.getErrorThresholdPercentage())
                    .withCircuitBreakerRequestVolumeThreshold(hystrixHandle.getRequestVolumeThreshold())
                    .withCircuitBreakerSleepWindowInMilliseconds(hystrixHandle.getSleepWindowInMilliseconds());

    return HystrixObservableCommand.Setter
            .withGroupKey(groupKey)
            .andCommandKey(commandKey)
            .andCommandPropertiesDefaults(propertiesSetter);
}
 
Example #20
Source File: BookingCommand.java    From resilient-transport-service with Apache License 2.0 5 votes vote down vote up
public BookingCommand(BookingServiceRequestDTO bookingServiceRequestDTO, RestTemplate restTemplate, boolean secondTry) {
    super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("BookingServiceClientGroup"))
        .andCommandKey(HystrixCommandKey.Factory.asKey("BookingServiceClient")));

    this.bookingServiceRequestDTO = bookingServiceRequestDTO;
    this.restTemplate = restTemplate;
    this.secondTry = secondTry;
}
 
Example #21
Source File: HystrixConcurrencyStrategyTests.java    From servicecomb-pack with Apache License 2.0 5 votes vote down vote up
public TestCircuitBreakerCommand(String name, OmegaContext omegaContext) {
  super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ThreadPoolTestGroup"))
      .andCommandKey(HystrixCommandKey.Factory.asKey("testCommandKey"))
      .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(name))
      .andThreadPoolPropertiesDefaults(
          HystrixThreadPoolProperties.Setter()
              .withMaxQueueSize(10)
              .withCoreSize(3)
              .withMaximumSize(3)
      )

  );
  this.omegaContext = omegaContext;
}
 
Example #22
Source File: DubboHystrixCommand.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public DubboHystrixCommand(Invoker<?> invoker,Invocation invocation){
    super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(invoker.getInterface().getName()))
                .andCommandKey(HystrixCommandKey.Factory.asKey(String.format("%s_%d", invocation.getMethodName(),
          invocation.getArguments() == null ? 0 : invocation.getArguments().length)))
          .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                                        .withCircuitBreakerRequestVolumeThreshold(20)//10秒钟内至少19此请求失败,熔断器才发挥起作用
                                        .withCircuitBreakerSleepWindowInMilliseconds(30000)//熔断器中断请求30秒后会进入半打开状态,放部分流量过去重试
                                        .withCircuitBreakerErrorThresholdPercentage(50)//错误率达到50开启熔断保护
                                        .withExecutionTimeoutEnabled(false))//使用dubbo的超时,禁用这里的超时
          .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(getThreadPoolCoreSize(invoker.getUrl()))));//线程池为30
   
    
    this.invoker=invoker;
    this.invocation=invocation;
}
 
Example #23
Source File: MessageInvokeCommandForThreadIsolation.java    From pmq with Apache License 2.0 5 votes vote down vote up
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;		
}
 
Example #24
Source File: CommandWithFallbackViaNetwork.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
public FallbackViaNetwork(int id) {
    super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceX"))
            .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueFallbackCommand"))
            // use a different threadpool for the fallback command
            // so saturating the RemoteServiceX pool won't prevent
            // fallbacks from executing
            .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("RemoteServiceXFallback")));
    this.id = id;
}
 
Example #25
Source File: EventNotifierDispatcher.java    From astrix with Apache License 2.0 5 votes vote down vote up
@Override
public void markCommandExecution(HystrixCommandKey key, 
								 ExecutionIsolationStrategy isolationStrategy, 
								 int duration,
								 List<HystrixEventType> eventsDuringExecution) {
	strategymapping.getHystrixStrategies(key)
				   .getHystrixEventNotifier()
				   .markCommandExecution(key, isolationStrategy, duration, eventsDuringExecution);
}
 
Example #26
Source File: FailedServiceInvocationLogger.java    From astrix with Apache License 2.0 5 votes vote down vote up
private Consumer<HystrixEventType> createNonBeanInvocationCommandLogger(HystrixCommandKey key) {
	return eventType -> {
		switch (eventType) {
		case FAILURE:
		case SEMAPHORE_REJECTED:
		case THREAD_POOL_REJECTED:
		case TIMEOUT:
		case SHORT_CIRCUITED:
			log.info(String.format("Aborted command execution: cause=%s astrixBean=null hystrixCommandKey=%s", eventType, key.name()));
			break;
		default:
			// Do nothing
		}
	};
}
 
Example #27
Source File: FailedServiceInvocationLogger.java    From astrix with Apache License 2.0 5 votes vote down vote up
public FailedBeanInvocationLogger(BeanConfiguration beanConfiguration, 
		AstrixBeanKey<?> beanKey,
		HystrixCommandKey hystrixCommandKey) {
	this.beanConfiguration = beanConfiguration;
	this.beanKey = beanKey;
	this.hystrixCommandKey = hystrixCommandKey;
}
 
Example #28
Source File: TestCommandKey.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testToHystrixCommandKey() {

  Invocation invocation = Mockito.mock(Invocation.class);

  Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class));
  Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1");
  Assert.assertNotNull(invocation);
  HystrixCommandKey hystrixCommandGroupKey = CommandKey.toHystrixCommandKey("groupname", invocation);
  Assert.assertNotNull(hystrixCommandGroupKey);
}
 
Example #29
Source File: HystrixCommandWithFallbackViaNetwork.java    From micro-service with MIT License 5 votes vote down vote up
public FallbackViaNetwork(int id) {
    super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceX"))
            .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueFallbackCommand"))
            // use a different threadpool for the fallback command so saturating the RemoteServiceX pool won't prevent fallbacks from executing
            .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("RemoteServiceXFallback")));
    this.id = id;
}
 
Example #30
Source File: HystrixCommandFacadeTest.java    From astrix with Apache License 2.0 5 votes vote down vote up
private int getEventCountForCommand(HystrixRollingNumberEvent hystrixRollingNumberEvent) {
	HystrixFaultToleranceFactory faultTolerance = (HystrixFaultToleranceFactory) AstrixApplicationContext.class.cast(this.context).getInstance(BeanFaultToleranceFactorySpi.class);
	HystrixCommandKey commandKey = faultTolerance.getCommandKey(AstrixBeanKey.create(Ping.class));
	HystrixCommandMetrics metrics = HystrixCommandMetrics.getInstance(commandKey);
	int currentConcurrentExecutionCount = (int) metrics.getCumulativeCount(hystrixRollingNumberEvent);
	return currentConcurrentExecutionCount;
}