com.netflix.hystrix.strategy.concurrency.HystrixRequestContext Java Examples

The following examples show how to use com.netflix.hystrix.strategy.concurrency.HystrixRequestContext. 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: CommandWithFallbackViaNetwork.java    From tools-journey with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    try {
        assertEquals(null, new CommandWithFallbackViaNetwork(1).execute());

        HystrixInvokableInfo<?> command1 = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().toArray(new HystrixInvokableInfo<?>[2])[0];
        assertEquals("GetValueCommand", command1.getCommandKey().name());
        assertTrue(command1.getExecutionEvents().contains(HystrixEventType.FAILURE));

        HystrixInvokableInfo<?> command2 = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().toArray(new HystrixInvokableInfo<?>[2])[1];
        assertEquals("GetValueFallbackCommand", command2.getCommandKey().name());
        assertTrue(command2.getExecutionEvents().contains(HystrixEventType.FAILURE));
    } finally {
        context.shutdown();
    }
}
 
Example #4
Source File: HystrixGrayTrackWebConfiguration.java    From spring-cloud-gray with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnProperty(value = "gray.client.runenv", havingValue = "web", matchIfMissing = true)
public GrayTrackFilter grayTrackFilter(
        GrayTrackHolder grayTrackHolder,
        RequestLocalStorage requestLocalStorage) {
    return new GrayTrackFilter(grayTrackHolder, requestLocalStorage) {
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            if (!HystrixRequestContext.isCurrentThreadInitialized()) {
                HystrixRequestContext.initializeContext();
            }
            try {
                super.doFilter(request, response, chain);
            } finally {
                if (HystrixRequestContext.isCurrentThreadInitialized()) {
                    HystrixRequestContext.getContextForCurrentThread().shutdown();
                }
            }
        }
    };
}
 
Example #5
Source File: CommandUsingRequestCacheInvalidation.java    From tools-journey with Apache License 2.0 6 votes vote down vote up
@Test
public void getGetSetGet() {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    try {
        assertEquals("ValueBeforeSet_1", new GetterCommand(1).execute());
        GetterCommand commandAgainstCache = new GetterCommand(1);
        assertEquals("ValueBeforeSet_1", commandAgainstCache.execute());
        // confirm it executed against cache the second time
        assertTrue(commandAgainstCache.isResponseFromCache());
        // set the new value
        new SetterCommand(1, "ValueAfterSet_").execute();
        // fetch it again
        GetterCommand commandAfterSet = new GetterCommand(1);
        // the getter should return with the new prefix, not the value from cache
        assertFalse(commandAfterSet.isResponseFromCache());
        assertEquals("ValueAfterSet_1", commandAfterSet.execute());
    } finally {
        context.shutdown();
    }
}
 
Example #6
Source File: QuickStart.java    From javabase with Apache License 2.0 6 votes vote down vote up
private static void commandWithFallbackViaNetworkTest() {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    try {
         log.info(new CommandWithFallbackViaNetwork(1).execute());

        HystrixInvokableInfo<?> command1 = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().toArray(new HystrixInvokableInfo<?>[2])[0];
        log.info(command1.getCommandKey().name());
        log.info(""+command1.getExecutionEvents().contains(HystrixEventType.FAILURE));

        HystrixInvokableInfo<?> command2 = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().toArray(new HystrixInvokableInfo<?>[2])[1];
        log.info(command2.getCommandKey().name());
        log.info(""+command2.getExecutionEvents().contains(HystrixEventType.FAILURE));
    } finally {
        context.shutdown();
    }
}
 
Example #7
Source File: HystrixRequestContextServletFilter.java    From spring-cloud-kubernetes with Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    try {
        chain.doFilter(request, response);
    } finally {
        context.shutdown();
    }
}
 
Example #8
Source File: BizkeeperCommand.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
protected String getCacheKey() {
  if (HystrixRequestContext.isCurrentThreadInitialized()) {
    StringBuilder sb = new StringBuilder();
    sb.append(this.getCommandGroup().name());
    sb.append("-");
    sb.append(this.getCommandKey().name());
    return sb.toString();
  } else {
    return super.getCacheKey();
  }
}
 
Example #9
Source File: CommandUsingRequestCache.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithoutCacheHits() {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    try {
        assertTrue(new CommandUsingRequestCache(2).execute());
        assertFalse(new CommandUsingRequestCache(1).execute());
        assertTrue(new CommandUsingRequestCache(0).execute());
        assertTrue(new CommandUsingRequestCache(58672).execute());
    } finally {
        context.shutdown();
    }
}
 
Example #10
Source File: CommandUsingRequestCache.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithCacheHits() {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    try {
        CommandUsingRequestCache command2a = new CommandUsingRequestCache(2);
        CommandUsingRequestCache command2b = new CommandUsingRequestCache(2);

        assertTrue(command2a.execute());
        // this is the first time we've executed this command with the value of "2" so it should not be from cache
        assertFalse(command2a.isResponseFromCache());

        assertTrue(command2b.execute());
        // this is the second time we've executed this command with the same value so it should return from cache
        assertTrue(command2b.isResponseFromCache());
    } finally {
        context.shutdown();
    }

    // start a new request context
    context = HystrixRequestContext.initializeContext();
    try {
        CommandUsingRequestCache command3b = new CommandUsingRequestCache(2);
        assertTrue(command3b.execute());
        // this is a new request context so this should not come from cache
        assertFalse(command3b.isResponseFromCache());
    } finally {
        context.shutdown();
    }
}
 
Example #11
Source File: HystrixFilter.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    try {
        filterChain.doFilter(servletRequest,servletResponse);
    }finally {
        context.shutdown();
    }
}
 
Example #12
Source File: HystrixContextFilter.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HystrixRequestContext hystrixRequestContext = HystrixRequestContext.initializeContext();
    initAllContext(request);
    try {
        chain.doFilter(request, response);
    } finally {
        ingestResponseBasedMetrics(response);
        // Log all the failed Hystrix commands before shutting down context
        logFailedHystrixCommands(request);
        shutdownAllContext(hystrixRequestContext);
    }
}
 
Example #13
Source File: PoseidonConsumer.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
public final AsyncConsumerResult consume(AsyncConsumerRequest consumerRequest) {
    Map<String, String> caseInsensitiveHeaders = Optional.ofNullable(consumerRequest.getHeaders()).orElse(Collections.emptyMap()).entrySet().stream().collect(Collectors.toMap(
            e -> e.getKey().toLowerCase(),
            Map.Entry::getValue
    ));

    PoseidonRequest request = new PoseidonAsyncRequest(consumerRequest.getUrl(), Collections.emptyMap(), caseInsensitiveHeaders, consumerRequest.getParameters());
    request.setAttribute(METHOD, consumerRequest.getHttpMethod());

    if (consumerRequest.getPayload() != null) {
        request.setAttribute(BODY_BYTES, consumerRequest.getPayload());
    }

    HystrixRequestContext hystrixRequestContext = HystrixRequestContext.initializeContext();
    initAllContext(request);

    PoseidonResponse response = null;
    try {
        response = new PoseidonResponse();
        this.application.handleRequest(request, response);
        return new AsyncConsumerResult(AsyncResultState.SUCCESS);
    } catch (Throwable throwable) {
        logger.error("Unexpected exception while consuming async event", throwable);
        return new AsyncConsumerResult(AsyncResultState.FAILURE);
    } finally {
        ingestResponseBasedMetrics(response);
        logFailedHystrixCommands(consumerRequest);
        shutdownAllContext(hystrixRequestContext);
    }
}
 
Example #14
Source File: ContextInducedBlock.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
protected ContextInducedBlock(Block block) {
    this.block = block;
    parentContext = RequestContext.getContextMap();
    serviceContextState = ServiceContext.getState();
    parentThreadState = HystrixRequestContext.getContextForCurrentThread();
    mdcContext = MDC.getCopyOfContextMap();
    serverSpan = Brave.getServerSpanThreadBinder().getCurrentServerSpan();
}
 
Example #15
Source File: ContextInducedBlock.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
protected void initAllContext(Request request) {
    existingState = HystrixRequestContext.getContextForCurrentThread();
    RequestContext.initialize(parentContext);
    ServiceContext.initialize(serviceContextState);
    HystrixRequestContext.setContextOnCurrentThread(parentThreadState);
    if (mdcContext != null) {
        MDC.setContextMap(mdcContext);
    }
    // Parent thread span info is passed onto filter thread using Brave's ThreadLocal implementation
    if (serverSpan != null && serverSpan.getSpan() != null) {
        Brave.getServerSpanThreadBinder().setCurrentSpan(serverSpan);
    }
    startTrace(block, request);
}
 
Example #16
Source File: ContextInducedBlock.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
protected void shutdownAllContext() {
    endTrace(block, success);
    RequestContext.shutDown();
    ServiceContext.shutDown();
    HystrixRequestContext.setContextOnCurrentThread(existingState);
    MDC.clear();
    Brave.getServerSpanThreadBinder().setCurrentSpan(null);
}
 
Example #17
Source File: SWHystrixLifecycleForwardingRequestVariable.java    From skywalking with Apache License 2.0 5 votes vote down vote up
/**
 * Return null if the {@link HystrixRequestContext} has not been initialized for the current thread.
 * <p>
 * If {@link HystrixRequestContext} has been initialized then call method in superclass:
 * {@link HystrixRequestVariableDefault#get()}
 */
@Override
public T get() {
    if (!HystrixRequestContext.isCurrentThreadInitialized()) {
        return null;
    }
    return super.get();
}
 
Example #18
Source File: RibbonTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testHystrixCache() throws IOException {
    // LogManager.getRootLogger().setLevel((Level)Level.DEBUG);
    MockWebServer server = new MockWebServer();
    String content = "Hello world";
    MockResponse response = new MockResponse()
        .setResponseCode(200)
        .setHeader("Content-type", "text/plain")
        .setBody(content);
    server.enqueue(response);
    
    server.enqueue(response);       
    server.play();
    
    HttpResourceGroup group = Ribbon.createHttpResourceGroupBuilder("myclient").build();
    HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class)
            .withUriTemplate("http://localhost:" + server.getPort())
            .withMethod("GET")
            .withRequestCacheKey("xyz")
            .build();
    RibbonRequest<ByteBuf> request = template
            .requestBuilder().build();
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    try {
        RibbonResponse<ByteBuf> ribbonResponse = request.withMetadata().execute();
        assertFalse(ribbonResponse.getHystrixInfo().isResponseFromCache());
        ribbonResponse = request.withMetadata().execute();
        assertTrue(ribbonResponse.getHystrixInfo().isResponseFromCache());
    } finally {
        context.shutdown();
    }
}
 
Example #19
Source File: AuthHystrixConcurrencyStrategy.java    From spring-cloud-shop with MIT License 5 votes vote down vote up
/**
 * Call v.
 *
 * @return the v
 * @throws Exception the exception
 */
@Override
public V call() throws Exception {
    HystrixRequestContext existingState = HystrixRequestContext.getContextForCurrentThread();
    try {
        HystrixRequestContext.setContextOnCurrentThread(this.hystrixRequestContext);
        return this.delegate.call();
    } finally {
        HystrixRequestContext.setContextOnCurrentThread(existingState);
    }
}
 
Example #20
Source File: HystrixRequestContextFilter.java    From code with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    try {
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        context.shutdown();
    }
}
 
Example #21
Source File: FwHystrixCommondFlushCache.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws ExecutionException, InterruptedException {
        HystrixRequestContext context = HystrixRequestContext.initializeContext();
        for (int i = 0; i <5 ; i++) {
            FwHystrixCommondFlushCache test = new FwHystrixCommondFlushCache("test");
            log.info(test.execute());
//            FwHystrixCommondFlushCache.flushCache("test");
        }
        context.shutdown();
    }
 
Example #22
Source File: FwHystrixCollapser.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws ExecutionException, InterruptedException {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    Future<String> tesFuture1 = new FwHystrixCollapser("test1").queue();
    Future<String> tesFuture2 = new FwHystrixCollapser("test2").queue();
    log.info(tesFuture1.get());
    log.info(tesFuture2.get());
    context.shutdown();
}
 
Example #23
Source File: FwHystrixCommondCache.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws ExecutionException, InterruptedException {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    for (int i = 0; i <5 ; i++) {
        FwHystrixCommondCache test = new FwHystrixCommondCache("test");
        log.info(test.execute());
    }
    context.shutdown();
}
 
Example #24
Source File: HystrixLocalStorageCycle.java    From spring-cloud-gray with Apache License 2.0 5 votes vote down vote up
@Override
public void initContext() {
    if (!HystrixRequestContext.isCurrentThreadInitialized()) {
        HystrixRequestContext.initializeContext();
        hystrixRequestContextInitialized.set(true);
    }
}
 
Example #25
Source File: HystrixLocalStorageCycle.java    From spring-cloud-gray with Apache License 2.0 5 votes vote down vote up
@Override
public void closeContext() {
    Boolean hystrixReqCxtInited = hystrixRequestContextInitialized.get();
    if (hystrixReqCxtInited != null) {
        hystrixRequestContextInitialized.remove();
        if (hystrixReqCxtInited && HystrixRequestContext.isCurrentThreadInitialized()) {
            HystrixRequestContext.getContextForCurrentThread().shutdown();
        }

    }
}
 
Example #26
Source File: CoreHeaderInterceptor.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
private static void initHystrixRequestContext(String labels) {
	log.info("LABEL={}", labels);
	if (!HystrixRequestContext.isCurrentThreadInitialized()) {
		HystrixRequestContext.initializeContext();
	}

	if (!StringUtils.isEmpty(labels)) {
		CoreHeaderInterceptor.LABEL.set(Arrays.asList(labels.split(CoreHeaderInterceptor.HEADER_LABEL_SPLIT)));
	} else {
		CoreHeaderInterceptor.LABEL.set(Collections.emptyList());
	}
}
 
Example #27
Source File: ClassController.java    From JetfireCloud with Apache License 2.0 5 votes vote down vote up
@GetMapping("/classes")
public Result hello(@RequestParam String name) {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    Result users = classService.users(name);
    context.close();
    return users;
}
 
Example #28
Source File: ClassController.java    From JetfireCloud with Apache License 2.0 5 votes vote down vote up
@PostMapping("/classes")
public Result hello(@RequestBody Map<String, String> params) {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    Result users = classService.users(params);
    context.close();
    return users;
}
 
Example #29
Source File: CoreHeaderInterceptor.java    From paascloud-master with Apache License 2.0 4 votes vote down vote up
private static void shutdownHystrixRequestContext() {
	if (HystrixRequestContext.isCurrentThreadInitialized()) {
		HystrixRequestContext.getContextForCurrentThread().shutdown();
	}
}
 
Example #30
Source File: BettingServiceTest.java    From hystrix_lab with MIT License 4 votes vote down vote up
/**
 * Test - GetHorsesInRace - Uses Caching
 */
@Test
public void testWithCacheHits() {
	
	HystrixRequestContext context = HystrixRequestContext.initializeContext();
	
	try {
		CommandGetHorsesInRaceWithCaching commandFirst = new CommandGetHorsesInRaceWithCaching(mockService, RACE_1);
		CommandGetHorsesInRaceWithCaching commandSecond = new CommandGetHorsesInRaceWithCaching(mockService, RACE_1);

		commandFirst.execute();
		// this is the first time we've executed this command with
		// the value of "2" so it should not be from cache
		assertFalse(commandFirst.isResponseFromCache());

		verify(mockService).getHorsesInRace(RACE_1);
		verifyNoMoreInteractions(mockService);

		commandSecond.execute();
		// this is the second time we've executed this command with
		// the same value so it should return from cache
		assertTrue(commandSecond.isResponseFromCache());

	} finally {
		context.shutdown();
	}

	// start a new request context
	context = HystrixRequestContext.initializeContext();
	try {
		CommandGetHorsesInRaceWithCaching commandThree = new CommandGetHorsesInRaceWithCaching(mockService, RACE_1);
		commandThree.execute();
		// this is a new request context so this
		// should not come from cache
		assertFalse(commandThree.isResponseFromCache());

		// Flush the cache
		HystrixRequestCache.getInstance(GETTER_KEY, HystrixConcurrencyStrategyDefault.getInstance()).clear(RACE_1);

	} finally {
		context.shutdown();
	}
}