org.springframework.web.client.AsyncRestTemplate Java Examples
The following examples show how to use
org.springframework.web.client.AsyncRestTemplate.
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: WingtipsSpringUtilTest.java From wingtips with Apache License 2.0 | 6 votes |
@DataProvider(value = { "true", "false" }) @Test public void createTracingEnabledAsyncRestTemplate_with_tag_and_span_naming_args_returns_AsyncRestTemplate_with_wingtips_interceptor_added_with_expected_fields( boolean subspanOptionOn ) { // when AsyncRestTemplate result = WingtipsSpringUtil.createTracingEnabledAsyncRestTemplate( subspanOptionOn, tagStrategyMock, tagAdapterMock ); // then assertThat(result.getInterceptors()).hasSize(1); assertThat(result.getInterceptors().get(0)).isInstanceOf(WingtipsAsyncClientHttpRequestInterceptor.class); verifyInterceptorFieldValues( result.getInterceptors().get(0), subspanOptionOn, tagStrategyMock, tagAdapterMock ); }
Example #2
Source File: AsyncLoadBalancerAutoConfigurationTests.java From spring-cloud-commons with Apache License 2.0 | 6 votes |
@Test public void multipleRestTemplates() { ConfigurableApplicationContext context = init(TwoRestTemplates.class); final Map<String, AsyncRestTemplate> restTemplates = context .getBeansOfType(AsyncRestTemplate.class); then(restTemplates).isNotNull(); Collection<AsyncRestTemplate> templates = restTemplates.values(); then(templates).hasSize(2); TwoRestTemplates.Two two = context.getBean(TwoRestTemplates.Two.class); then(two.loadBalanced).isNotNull(); assertLoadBalanced(two.loadBalanced); then(two.nonLoadBalanced).isNotNull(); then(two.nonLoadBalanced.getInterceptors()).isEmpty(); }
Example #3
Source File: ITTracingAsyncClientHttpRequestInterceptor.java From brave with Apache License 2.0 | 6 votes |
@Override protected void get(AsyncClientHttpRequestFactory client, String path, BiConsumer<Integer, Throwable> callback) { AsyncRestTemplate restTemplate = new AsyncRestTemplate(client); restTemplate.setInterceptors(Collections.singletonList(interceptor)); restTemplate.getForEntity(url(path), String.class) .addCallback(new ListenableFutureCallback<ResponseEntity<String>>() { @Override public void onFailure(Throwable throwable) { if (throwable instanceof HttpStatusCodeException) { callback.accept(((HttpStatusCodeException) throwable).getRawStatusCode(), null); } else { callback.accept(null, throwable); } } @Override public void onSuccess(ResponseEntity<String> entity) { callback.accept(entity.getStatusCodeValue(), null); } }); }
Example #4
Source File: WingtipsSpringUtil.java From wingtips with Apache License 2.0 | 6 votes |
/** * @param tagAndNamingStrategy The span tag and naming strategy to use - cannot be null. If you really want no * tag and naming strategy, then pass in {@link NoOpHttpTagStrategy#getDefaultInstance()}. * @param tagAndNamingAdapter The tag and naming adapter to use - cannot be null. If you really want no tag and * naming adapter, then pass in {@link NoOpHttpTagAdapter#getDefaultInstance()}. * @return A new {@link AsyncRestTemplate} instance with a {@link WingtipsAsyncClientHttpRequestInterceptor} * already added, and with the subspan option and tag/naming strategy and adapter set to the given arguments. */ public static AsyncRestTemplate createTracingEnabledAsyncRestTemplate( boolean surroundCallsWithSubspan, HttpTagAndSpanNamingStrategy<HttpRequest, ClientHttpResponse> tagAndNamingStrategy, HttpTagAndSpanNamingAdapter<HttpRequest, ClientHttpResponse> tagAndNamingAdapter ) { AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate(); asyncRestTemplate.getInterceptors().add( new WingtipsAsyncClientHttpRequestInterceptor( surroundCallsWithSubspan, tagAndNamingStrategy, tagAndNamingAdapter ) ); return asyncRestTemplate; }
Example #5
Source File: WingtipsSpringUtilTest.java From wingtips with Apache License 2.0 | 6 votes |
@DataProvider(value = { "true", "false" }) @Test public void createTracingEnabledAsyncRestTemplate_single_arg_returns_AsyncRestTemplate_with_wingtips_interceptor_added_with_expected_fields( boolean subspanOptionOn ) { // when AsyncRestTemplate result = WingtipsSpringUtil.createTracingEnabledAsyncRestTemplate(subspanOptionOn); // then assertThat(result.getInterceptors()).hasSize(1); assertThat(result.getInterceptors().get(0)).isInstanceOf(WingtipsAsyncClientHttpRequestInterceptor.class); verifyInterceptorFieldValues( result.getInterceptors().get(0), subspanOptionOn, ZipkinHttpTagStrategy.getDefaultInstance(), SpringHttpClientTagAdapter.getDefaultInstance() ); }
Example #6
Source File: DockerServiceFactory.java From haven-platform with Apache License 2.0 | 6 votes |
private AsyncRestTemplate createNewRestTemplate(String addr) { // we use async client because usual client does not allow to interruption in some cases NettyRequestFactory factory = new NettyRequestFactory(); if(AddressUtils.isHttps(addr)) { try { initSsl(addr, factory); } catch (Exception e) { log.error("", e); } } final AsyncRestTemplate restTemplate = new AsyncRestTemplate(factory); List<AsyncClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add(new HttpAuthInterceptor(registryRepository)); if(!StringUtils.isEmpty(agentPassword)) { interceptors.add(new BasicAuthAsyncInterceptor("admin", agentPassword)); } restTemplate.setInterceptors(interceptors); return restTemplate; }
Example #7
Source File: AsyncRestTemplateCircuitBreakerAutoConfiguration.java From spring-cloud-formula with Apache License 2.0 | 6 votes |
@Bean public SmartInitializingSingleton loadBalancedAsyncRestTemplateInitializer2( final List<AsyncRestTemplateCustomizer> customizers) { return new SmartInitializingSingleton() { @Override public void afterSingletonsInstantiated() { logger.info("init AsyncRestTemplateCircuitBreaker start"); for (AsyncRestTemplate restTemplate : AsyncRestTemplateCircuitBreakerAutoConfiguration.this .restTemplates) { AsyncRestTemplateCircuitInterceptor interceptor = new AsyncRestTemplateCircuitInterceptor(circuitBreakerCore); logger.info("add AsyncRestTemplateCircuitInterceptor first"); List<AsyncClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors(); interceptors.add(0, interceptor); restTemplate.setInterceptors(interceptors); } logger.info("init AsyncRestTemplateCircuitBreaker end"); } }; }
Example #8
Source File: AsyncRestTemplateTest.java From sofa-tracer with Apache License 2.0 | 6 votes |
public void testPostFromEntity() throws IOException, InterruptedException, ExecutionException { AsyncRestTemplate restTemplate = SofaTracerRestTemplateBuilder.buildAsyncRestTemplate(); PostBody postBody = new PostBody(); postBody.setName("weiheng"); HttpEntity<PostBody> entity = new HttpEntity<PostBody>(postBody); ListenableFuture<ResponseEntity<PostBody>> responseEntityListenableFuture = restTemplate .postForEntity(urlHttpPrefix, entity, PostBody.class); ResponseEntity<PostBody> postBodyResponseEntity = responseEntityListenableFuture.get(); Assert.assertTrue(postBodyResponseEntity.getBody().getName().equals("weiheng")); Thread.sleep(1000); //wait for async output List<String> contents = FileUtils.readLines(new File( logDirectoryPath + File.separator + RestTemplateLogEnum.REST_TEMPLATE_DIGEST.getDefaultLogName())); assertTrue(contents.size() == 2); //stat log List<String> statContents = FileUtils.readLines(new File( logDirectoryPath + File.separator + RestTemplateLogEnum.REST_TEMPLATE_STAT.getDefaultLogName())); assertTrue(statContents.size() == 2); }
Example #9
Source File: ClusterConfigFetcherTest.java From haven-platform with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") DockerServiceImpl dockerService() { ClusterConfig config = ClusterConfigImpl.builder().host("localhost:2375").build(); AsyncRestTemplate restTemplate = new AsyncRestTemplate(); restTemplate.setInterceptors( Collections.singletonList( new HttpAuthInterceptor(null))); return DockerServiceImpl.builder() .config(config) .cluster("test") .restTemplate(restTemplate) .nodeInfoProvider(mock(NodeInfoProvider.class)) .eventConsumer(mock(MessageBus.class)) .objectMapper(new ObjectMapper()) .build(); }
Example #10
Source File: DockerServiceImplTest.java From haven-platform with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") DockerServiceImpl dockerService() { ClusterConfig config = ClusterConfigImpl.builder() .host("172.31.0.12:2375").build(); AsyncRestTemplate restTemplate = new AsyncRestTemplate(); RegistryRepository registryRepository = mock(RegistryRepository.class); restTemplate.setInterceptors( Collections.singletonList( new HttpAuthInterceptor(registryRepository))); return DockerServiceImpl.builder() .config(config) .cluster("test") .restTemplate(restTemplate) .nodeInfoProvider(mock(NodeInfoProvider.class)) .eventConsumer(mock(MessageBus.class)) .objectMapper(new ObjectMapper()) .build(); }
Example #11
Source File: ComposeExecutorTest.java From haven-platform with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("unchecked") @Ignore public void testLaunchTask() throws Exception { ClusterConfig config = ClusterConfigImpl.builder().host("localhost:2375").build(); DockerService dockerService = DockerServiceImpl.builder() .config(config) .restTemplate(new AsyncRestTemplate()) .nodeInfoProvider(mock(NodeInfoProvider.class)) .eventConsumer(mock(MessageBus.class)) .objectMapper(new ObjectMapper()) .cluster("test") .build(); ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("docker-compose.yml").getFile()); ComposeResult composeResult = composeExecutor.up(ComposeArg.builder().file(file).runUpdate(false).build(), dockerService); Assert.notNull(composeResult); }
Example #12
Source File: AsyncRestTemplateRateLimiterConfiguration.java From spring-cloud-formula with Apache License 2.0 | 6 votes |
@Bean public SmartInitializingSingleton loadBalancedAsyncRestTemplateInitializer2( final List<AsyncRestTemplateCustomizer> customizers) { return new SmartInitializingSingleton() { @Override public void afterSingletonsInstantiated() { logger.info("Init AsyncRestTemplateRateLimiterConfiguration"); for (AsyncRestTemplate restTemplate : AsyncRestTemplateRateLimiterConfiguration.this.restTemplates) { List<AsyncClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors(); logger.debug("AsyncRestTemplate init start, interceptor size:" + interceptors.size()); AsyncClientHttpRequestInterceptor interceptor = new AsyncRestTemplateRateLimiterInterceptor(serviceName); interceptors.add(0, interceptor); logger.debug("AsyncRestTemplate init end, Add AsyncRestTemplateRateLimiterInterceptor"); restTemplate.setInterceptors(interceptors); } } }; }
Example #13
Source File: AsyncLoadBalancerAutoConfiguration.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
@Bean public SmartInitializingSingleton loadBalancedAsyncRestTemplateInitializer( final List<AsyncRestTemplateCustomizer> customizers) { return () -> { for (AsyncRestTemplate restTemplate : AsyncRestTemplateCustomizerConfig.this.restTemplates) { for (AsyncRestTemplateCustomizer customizer : customizers) { customizer.customize(restTemplate); } } }; }
Example #14
Source File: SpringWebITest.java From java-specialagent with Apache License 2.0 | 5 votes |
private static boolean makeAsyncCall() throws Exception { final AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate(); final int status = asyncRestTemplate.getForEntity("http://www.google.com", String.class).get(10, TimeUnit.SECONDS).getStatusCode().value(); if (200 != status) throw new AssertionError("ERROR: response: " + status); final CountDownLatch latch = new CountDownLatch(1); final Span parent = GlobalTracer.get().buildSpan("parent").start(); try(final Scope scope = GlobalTracer.get().activateSpan(parent)) { asyncRestTemplate.getForEntity("http://www.google.com", String.class) .addCallback(new ListenableFutureCallback<ResponseEntity<String>>() { @Override public void onSuccess(final ResponseEntity<String> result) { TestUtil.checkActiveSpan(); latch.countDown(); } @Override public void onFailure(final Throwable t) { TestUtil.checkActiveSpan(); latch.countDown(); } }); } finally { parent.finish(); } latch.await(15, TimeUnit.SECONDS); return true; }
Example #15
Source File: RestTemplateAutoConfiguration.java From summerframework with Apache License 2.0 | 5 votes |
@Bean public SmartInitializingSingleton metricsAsyncRestTemplateInitializer( final ObjectProvider<List<AsyncRestTemplate>> asyncRestTemplatesProvider, final RestTemplatePostProcessor customizer) { return () -> { final List<AsyncRestTemplate> asyncRestTemplates = asyncRestTemplatesProvider.getIfAvailable(); if (!CollectionUtils.isEmpty(asyncRestTemplates)) { asyncRestTemplates.forEach(customizer::customize); } }; }
Example #16
Source File: RestTemplatePostProcessor.java From summerframework with Apache License 2.0 | 5 votes |
public void customize(final AsyncRestTemplate restTemplate) { if (restTemplate.getInterceptors().contains(this.metricsClientHttpRequestInterceptor)) { return; } UriTemplateHandler templateHandler = restTemplate.getUriTemplateHandler(); templateHandler = this.metricsClientHttpRequestInterceptor.createUriTemplateHandler(templateHandler); restTemplate.setUriTemplateHandler(templateHandler); List<AsyncClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add(this.metricsClientHttpRequestInterceptor); interceptors.addAll(restTemplate.getInterceptors()); restTemplate.setInterceptors(interceptors); }
Example #17
Source File: SofaTracerRestTemplateBuilder.java From sofa-tracer with Apache License 2.0 | 5 votes |
@Deprecated public static AsyncRestTemplate buildAsyncRestTemplate() { AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate(); List<AsyncClientHttpRequestInterceptor> interceptors = new ArrayList<AsyncClientHttpRequestInterceptor>(); AsyncRestTemplateRequestInterceptor asyncRestTemplateInterceptor = new AsyncRestTemplateRequestInterceptor( getRestTemplateTracer()); interceptors.add(asyncRestTemplateInterceptor); asyncRestTemplate.setInterceptors(interceptors); return asyncRestTemplate; }
Example #18
Source File: MyController.java From Hands-On-Reactive-Programming-in-Spring-5 with MIT License | 5 votes |
@RequestMapping(produces = MediaType.TEXT_PLAIN_VALUE) public ListenableFuture<?> requestData() { AsyncRestTemplate httpClient = new AsyncRestTemplate(); AsyncDatabaseClient databaseClient = new FakeAsyncDatabaseClient(); CompletionStage<String> completionStage = AsyncAdapters.toCompletion(httpClient.execute( "http://localhost:8080/hello", HttpMethod.GET, null, new HttpMessageConverterExtractor<>(String.class, messageConverters) )); return AsyncAdapters.toListenable(databaseClient.store(completionStage)); }
Example #19
Source File: AsyncRestTemplateTest.java From sofa-tracer with Apache License 2.0 | 5 votes |
public void testGetFromEntity() throws IOException, InterruptedException { AsyncRestTemplate restTemplate = SofaTracerRestTemplateBuilder.buildAsyncRestTemplate(); ListenableFuture<ResponseEntity<Map>> forEntity = restTemplate.getForEntity(urlHttpPrefix, Map.class); forEntity.addCallback(new ListenableFutureCallback<ResponseEntity<Map>>() { @Override public void onFailure(Throwable ex) { Assert.assertTrue(false); } @Override public void onSuccess(ResponseEntity<Map> result) { Assert.assertTrue(result.getBody().containsKey("name")); } }); Thread.sleep(1000); //wait for async output List<String> contents = FileUtils.readLines(new File( logDirectoryPath + File.separator + RestTemplateLogEnum.REST_TEMPLATE_DIGEST.getDefaultLogName())); assertTrue(contents.size() == 1); //stat log List<String> statContents = FileUtils.readLines(new File( logDirectoryPath + File.separator + RestTemplateLogEnum.REST_TEMPLATE_STAT.getDefaultLogName())); assertTrue(statContents.size() == 1); }
Example #20
Source File: AsyncServiceOne.java From Hands-On-Reactive-Programming-in-Spring-5 with MIT License | 5 votes |
@GetMapping public Future<?> process() { AsyncRestTemplate template = new AsyncRestTemplate(); SuccessCallback onSuccess = r -> System.out.println("Success"); FailureCallback onFailure = e -> System.out.println("Failure"); ListenableFuture<?> response = template.getForEntity( "http://localhost:" + PORT + "/api/v2/resource/b", ExamplesCollection.class ); response.addCallback(onSuccess, onFailure); return response; }
Example #21
Source File: AsyncRestTemplateBenchmarks.java From brave with Apache License 2.0 | 5 votes |
@Override protected AsyncRestTemplate newClient(HttpTracing httpTracing) { OkHttp3ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory(ok); AsyncRestTemplate result = new AsyncRestTemplate(factory); result.setInterceptors(Collections.singletonList( TracingAsyncClientHttpRequestInterceptor.create(httpTracing ))); return result; }
Example #22
Source File: MockRestServiceServer.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Create a {@code MockRestServiceServer} and set up the given * {@code AsyRestTemplate} with a mock {@link AsyncClientHttpRequestFactory}. * @param asyncRestTemplate the AsyncRestTemplate to set up for mock testing * @return the created mock server */ public static MockRestServiceServer createServer(AsyncRestTemplate asyncRestTemplate) { Assert.notNull(asyncRestTemplate, "'asyncRestTemplate' must not be null"); MockRestServiceServer mockServer = new MockRestServiceServer(); RequestMatcherClientHttpRequestFactory factory = mockServer.new RequestMatcherClientHttpRequestFactory(); asyncRestTemplate.setAsyncRequestFactory(factory); return mockServer; }
Example #23
Source File: AsyncLoadBalancerAutoConfigurationTests.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
private void assertLoadBalanced(AsyncRestTemplate restTemplate) { List<AsyncClientHttpRequestInterceptor> interceptors = restTemplate .getInterceptors(); then(interceptors).hasSize(1); AsyncClientHttpRequestInterceptor interceptor = interceptors.get(0); then(interceptor).isInstanceOf(AsyncLoadBalancerInterceptor.class); }
Example #24
Source File: AsyncLoadBalancerAutoConfigurationTests.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
@Test public void restTemplateGetsLoadBalancerInterceptor() { ConfigurableApplicationContext context = init(OneRestTemplate.class); final Map<String, AsyncRestTemplate> restTemplates = context .getBeansOfType(AsyncRestTemplate.class); then(restTemplates).isNotNull(); then(restTemplates.values()).hasSize(1); AsyncRestTemplate restTemplate = restTemplates.values().iterator().next(); then(restTemplate).isNotNull(); assertLoadBalanced(restTemplate); }
Example #25
Source File: TraceWebAsyncClientAutoConfiguration.java From spring-cloud-sleuth with Apache License 2.0 | 5 votes |
@PostConstruct public void init() { if (this.restTemplates != null) { for (AsyncRestTemplate restTemplate : this.restTemplates) { List<AsyncClientHttpRequestInterceptor> interceptors = new ArrayList<>( restTemplate.getInterceptors()); interceptors.add(this.clientInterceptor); restTemplate.setInterceptors(interceptors); } } }
Example #26
Source File: WingtipsSpringUtilTest.java From wingtips with Apache License 2.0 | 5 votes |
@Test public void createTracingEnabledAsyncRestTemplate_no_args_returns_AsyncRestTemplate_with_wingtips_interceptor_added_with_expected_fields() { // when AsyncRestTemplate result = WingtipsSpringUtil.createTracingEnabledAsyncRestTemplate(); // then assertThat(result.getInterceptors()).hasSize(1); assertThat(result.getInterceptors().get(0)).isInstanceOf(WingtipsAsyncClientHttpRequestInterceptor.class); verifyInterceptorFieldValues( result.getInterceptors().get(0), true, ZipkinHttpTagStrategy.getDefaultInstance(), SpringHttpClientTagAdapter.getDefaultInstance() ); }
Example #27
Source File: NIORestClient.java From micro-server with Apache License 2.0 | 5 votes |
public NIORestClient(AsyncRestTemplate template) { super(); this.template = template; MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setObjectMapper(JacksonUtil.getMapper()); template.getMessageConverters().add(converter); }
Example #28
Source File: SpringConfig.java From micro-server with Apache License 2.0 | 5 votes |
@Bean public NIORestClient restClient(){ HttpComponentsAsyncClientHttpRequestFactory rest = new HttpComponentsAsyncClientHttpRequestFactory(); rest.setConnectionRequestTimeout(connectionRequestTimeout); rest.setReadTimeout(readTimeout); rest.setConnectTimeout(connectTimeout); return new NIORestClient(new AsyncRestTemplate(rest)); }
Example #29
Source File: AsyncRestTemplateBenchmarks.java From brave with Apache License 2.0 | 4 votes |
@Override protected void close(AsyncRestTemplate client) { ok.dispatcher().executorService().shutdownNow(); }
Example #30
Source File: ResttemplateConfiguration.java From skywalking with Apache License 2.0 | 4 votes |
@Bean public AsyncRestTemplate asyncRestTemplate() { return new AsyncRestTemplate(); }