Java Code Examples for com.netflix.hystrix.strategy.concurrency.HystrixRequestContext#initializeContext()

The following examples show how to use com.netflix.hystrix.strategy.concurrency.HystrixRequestContext#initializeContext() . 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: 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 2
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 3
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 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: 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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
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 17
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();
	}
}
 
Example 18
Source File: HystrixRequestContextServletFilter.java    From SpringAll with MIT License 4 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    filterChain.doFilter(servletRequest, servletResponse);
    context.close();
}
 
Example 19
Source File: HystrixRequestContextServletFilter.java    From SpringAll with MIT License 4 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    filterChain.doFilter(servletRequest, servletResponse);
    context.close();
}
 
Example 20
Source File: BizkeeperRequestContext.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
public static BizkeeperRequestContext initializeContext() {
  return new BizkeeperRequestContext(HystrixRequestContext.initializeContext());
}