Java Code Examples for com.netflix.hystrix.HystrixCommandProperties#Setter

The following examples show how to use com.netflix.hystrix.HystrixCommandProperties#Setter . 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: TestBizkeeperCommand.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 2
Source File: TestBizkeeperCommand.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCacheKeyWithContextInitializedConsumer() {

  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 ConsumerBizkeeperCommand("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);
}
 
Example 3
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 4
Source File: TestBizkeeperCommand.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testConstructConsumer() {

  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 ConsumerBizkeeperCommand("groupname", invocation,
      HystrixObservableCommand.Setter
          .withGroupKey(CommandKey.toHystrixCommandGroupKey("groupname", invocation))
          .andCommandKey(CommandKey.toHystrixCommandKey("groupname", invocation))
          .andCommandPropertiesDefaults(setter));

  Observable<Response> response = bizkeeperCommand.construct();
  Assert.assertNotNull(response);
}
 
Example 5
Source File: HystrixMetricsTest.java    From javabase with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {


        CommandConfig.Setter setter = HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("HystrixMetrics-config"));
        setter.andCommandKey(HystrixCommandKey.Factory.asKey("HystrixMetrics-method"));
        //在调用方配置,被该调用方的所有方法的超时时间都是该值
        HystrixCommandProperties.Setter defaultSetter = HystrixCommandProperties.Setter();
        setter.andCommandPropertiesDefaults(defaultSetter);
        Observable<HystrixDashboardStream.DashboardData> dashboardDataOservable = HystrixDashboardStream.getInstance().observe();
        Observable<String> sampleStream = dashboardDataOservable.concatMap(new Func1<HystrixDashboardStream.DashboardData, Observable<String>>() {
            public Observable<String> call(HystrixDashboardStream.DashboardData dashboardData) {
                return Observable.from(SerialHystrixDashboardData.toMultipleJsonStrings(dashboardData));
            }
        });

        Subscription sampleSubscription = sampleStream.observeOn(Schedulers.io()).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable throwable) {

            }

            @Override
            public void onNext(String sampleDataAsString) {
                log.info("sampleDataAsString=" + sampleDataAsString);
            }
        });
        if (sampleSubscription.isUnsubscribed()) {
            sampleSubscription.unsubscribe();
        }

        for (; ; ) {
            new MetricsCommand(setter).execute();
        }
    }
 
Example 6
Source File: SayHelloCommand.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private SayHelloCommand(HystrixTestHelper.ExecutionOption executionOption, String commandGroup, String name, HystrixCommandProperties.Setter setter, long delayMs, Exception expectedException) {
    super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(commandGroup)).andCommandPropertiesDefaults(setter));
    this.executionOption = executionOption;
    this.name = name;
    this.expectedException = expectedException;
    this.delayMs = delayMs;
}
 
Example 7
Source File: TestBizkeeperCommand.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetCacheKeyConsumer() {

  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 ConsumerBizkeeperCommand("groupname", invocation,
      HystrixObservableCommand.Setter
          .withGroupKey(CommandKey.toHystrixCommandGroupKey("groupname", invocation))
          .andCommandKey(CommandKey.toHystrixCommandKey("groupname", invocation))
          .andCommandPropertiesDefaults(setter));

  String str = bizkeeperCommand.getCacheKey();
  Assert.assertNull(str);

  Response resp = Mockito.mock(Response.class);
  Mockito.when(resp.isFailed()).thenReturn(false);
  Assert.assertEquals(false, bizkeeperCommand.isFailedResponse(resp));
  Mockito.when(resp.isFailed()).thenReturn(true);
  InvocationException excp = Mockito.mock(InvocationException.class);
  Mockito.when(resp.getResult()).thenReturn(excp);
  Mockito.when(excp.getStatusCode()).thenReturn(400);
  Assert.assertEquals(false, bizkeeperCommand.isFailedResponse(resp));
  Mockito.when(resp.getResult()).thenReturn(excp);
  Mockito.when(excp.getStatusCode()).thenReturn(490);
  Assert.assertEquals(true, bizkeeperCommand.isFailedResponse(resp));
}
 
Example 8
Source File: HystrixCommandTest.java    From prometheus-hystrix with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldIncrementCounterHistogramOnCommandsRunIntoTimeout() {
    // given
    HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.defaultSetter()
            .withExecutionTimeoutEnabled(true)
            .withExecutionTimeoutInMilliseconds(1);

    // when
    final TestHystrixCommand command = new TestHystrixCommand("shouldCountCommandsRunIntoTimeout", commandProperties).willWait(1000);
    assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() {
            command.execute();
        }
    }).isExactlyInstanceOf(HystrixRuntimeException.class);

    // then
    assertThat(CollectorRegistry.defaultRegistry.getSampleValue(
            "exampleapp_hystrix_command_latency_execute_seconds_count",
            new String[]{"command_group", "command_name"},
            new String[]{"group_shouldCountCommandsRunIntoTimeout", "command_shouldCountCommandsRunIntoTimeout"}
    ))
            .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_shouldCountCommandsRunIntoTimeout", "command_shouldCountCommandsRunIntoTimeout"}
    ))
            .describedAs("counter of all executions in the histogram")
            .isEqualTo(1);
}
 
Example 9
Source File: TestBizkeeperHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
protected BizkeeperCommand createBizkeeperCommand(Invocation invocation) {
  HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
      .withRequestCacheEnabled(true)
      .withRequestLogEnabled(false);

  BizkeeperCommand bizkeeperCommand = new ConsumerBizkeeperCommand("groupname", invocation,
      HystrixObservableCommand.Setter
          .withGroupKey(CommandKey.toHystrixCommandGroupKey("groupname", invocation))
          .andCommandKey(CommandKey.toHystrixCommandKey("groupname", invocation))
          .andCommandPropertiesDefaults(setter));
  return bizkeeperCommand;
}
 
Example 10
Source File: SayHelloObservableCommand.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private SayHelloObservableCommand(HystrixTestHelper.ExecutionOption executionOption, String commandGroup, String name, HystrixCommandProperties.Setter setter, long delayMs, Exception expectedException) {
    super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(commandGroup)).andCommandPropertiesDefaults(setter));
    this.executionOption = executionOption;
    this.name = name;
    this.expectedException = expectedException;
    this.delayMs = delayMs;
}
 
Example 11
Source File: ConsumerBizkeeperHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
protected BizkeeperCommand createBizkeeperCommand(Invocation invocation) {
  HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
      .withRequestCacheEnabled(true)
      .withRequestLogEnabled(false);
  setCommonProperties(invocation, setter);

  BizkeeperCommand command = new ConsumerBizkeeperCommand(groupname, invocation,
      HystrixObservableCommand.Setter
          .withGroupKey(CommandKey.toHystrixCommandGroupKey(groupname, invocation))
          .andCommandKey(CommandKey.toHystrixCommandKey(groupname, invocation))
          .andCommandPropertiesDefaults(setter));
  return command;
}
 
Example 12
Source File: ProviderBizkeeperHanlder.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
protected BizkeeperCommand createBizkeeperCommand(Invocation invocation) {
  HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
      .withRequestCacheEnabled(false)
      .withRequestLogEnabled(false);
  setCommonProperties(invocation, setter);

  BizkeeperCommand command = new ProviderBizkeeperCommand(groupname, invocation,
      HystrixObservableCommand.Setter
          .withGroupKey(CommandKey.toHystrixCommandGroupKey(groupname, invocation))
          .andCommandKey(CommandKey.toHystrixCommandKey(groupname, invocation))
          .andCommandPropertiesDefaults(setter));
  return command;
}
 
Example 13
Source File: TestHystrixCommand.java    From prometheus-hystrix with Apache License 2.0 5 votes vote down vote up
public TestHystrixCommand(String key, HystrixCommandProperties.Setter commandProperties) {
    this(
            Setter
                    .withGroupKey(HystrixCommandGroupKey.Factory.asKey("group_" + key))
                    .andCommandKey(HystrixCommandKey.Factory.asKey("command_" + key))
                    .andCommandPropertiesDefaults(commandProperties)
    );
}
 
Example 14
Source File: HelloSemphor.java    From TakinRPC with Apache License 2.0 5 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.SEMAPHORE)//
                    .withExecutionIsolationSemaphoreMaxConcurrentRequests(10);
    return HystrixCommand.Setter.withGroupKey(groupkey).andCommandKey(commandkey)//
                    .andThreadPoolKey(threadpoolkey).andThreadPoolPropertiesDefaults(threadproperties)//
                    .andCommandPropertiesDefaults(commandproperty);
}
 
Example 15
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 16
Source File: HelloCommand.java    From TakinRPC with Apache License 2.0 5 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(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);
}
 
Example 17
Source File: HystrixCommandPropertiesExt.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
protected HystrixCommandPropertiesExt(HystrixCommandKey key, HystrixCommandProperties.Setter builder) {
  this(key, builder, "servicecomb");
}
 
Example 18
Source File: HttpRequestTemplate.java    From ribbon with Apache License 2.0 4 votes vote down vote up
protected HttpRequestTemplate(String name, HttpResourceGroup group, Class<? extends T> classType, HystrixObservableCommand.Setter setter,
                    HttpMethod method, HttpHeaders headers, ParsedTemplate uriTemplate,
                    FallbackHandler<T> fallbackHandler, ResponseValidator<HttpClientResponse<ByteBuf>> validator, CacheProviderWithKeyTemplate<T> cacheProvider,
                    ParsedTemplate hystrixCacheKeyTemplate) {
    this.group = group;
    this.name = name;
    this.classType = classType;
    this.method = method;
    this.parsedUriTemplate = uriTemplate;
    this.fallbackHandler = fallbackHandler;
    this.validator = validator;
    this.cacheProvider = cacheProvider;
    this.hystrixCacheKeyTemplate = hystrixCacheKeyTemplate;
    this.client = group.getClient();
    this.headers = headers;
    if (client instanceof LoadBalancingRxClient) {
        LoadBalancingRxClient ribbonClient = (LoadBalancingRxClient) client;
        maxResponseTime = ribbonClient.getResponseTimeOut();
        concurrentRequestLimit = ribbonClient.getMaxConcurrentRequests();
    } else {
        maxResponseTime = -1;
        concurrentRequestLimit = -1;
    }
    String cacheName = name + CACHE_HYSTRIX_COMMAND_SUFFIX;
    cacheSetter = HystrixObservableCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(cacheName))
            .andCommandKey(HystrixCommandKey.Factory.asKey(cacheName));
    HystrixCommandProperties.Setter cacheCommandProps = HystrixCommandProperties.Setter();
    cacheCommandProps.withExecutionIsolationThreadTimeoutInMilliseconds(DEFAULT_CACHE_TIMEOUT);
    cacheSetter.andCommandPropertiesDefaults(cacheCommandProps);
    if (setter != null) {
        this.setter = setter;
    } else {
        this.setter = HystrixObservableCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(client.name()))
                .andCommandKey(HystrixCommandKey.Factory.asKey(name()));
        HystrixCommandProperties.Setter commandProps = HystrixCommandProperties.Setter();
        if (maxResponseTime > 0) {
            commandProps.withExecutionIsolationThreadTimeoutInMilliseconds(maxResponseTime);
        }
        if (concurrentRequestLimit > 0) {
            commandProps.withExecutionIsolationSemaphoreMaxConcurrentRequests(concurrentRequestLimit);
        }
        this.setter.andCommandPropertiesDefaults(commandProps);
    }
}
 
Example 19
Source File: SayHelloCommand.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
private SayHelloCommand(HystrixTestHelper.ExecutionOption executionOption, String commandGroup, String name, HystrixCommandProperties.Setter setter, long delayMs) {
    this(executionOption, commandGroup, name, setter, delayMs, null);
}
 
Example 20
Source File: SayHelloObservableCommand.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
public static SayHelloObservableCommand createForException(String commandGroup, String name, Exception expectedException) {
    return new SayHelloObservableCommand(HystrixTestHelper.ExecutionOption.EXCEPTION, commandGroup, name, HystrixCommandProperties.Setter(), 0, expectedException);
}