Spring 4 AsyncRestTemplate + ListenableFuture Example

By Arvind Rai, August 23, 2014
On this page we will learn the use of Spring 4 AsyncRestTemplate and ListenableFuture. AsyncRestTemplate accesses the URL and return the output asynchronously. Output is in the form of ListenableFuture that has get() method to get the result. We will discuss here two methods exchange() and execute() of AsyncRestTemplate. Spring 4 provides AsyncRequestCallback class to prepare request object. Read below for complete story and examples.

org.springframework.web.client.AsyncRestTemplate

AsyncRestTemplate is the main class for client side HTTP access. The access is asynchronous. A URL can be invoked asynchronously within a program which will return ListenableFuture object.

org.springframework.util.concurrent.ListenableFuture

ListenableFuture has been derived from java.util.concurrent.Future class. ListenableFuture<T> provides the result of AsyncRestTemplate methods. It waits for the result. Using ListenableFuture.get() we fetch the output.

AsyncRestTemplate.exchange() Example

Here we will see the example of AsyncRestTemplate.exchange() method. It executes the given URI using given HTTP method and returns the response as ListenableFuture of org.springframework.http.ResponseEntity.
ExchangeMethodExample.java
package com.concretepage;
import java.util.concurrent.ExecutionException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.client.AsyncRestTemplate;
public class ExchangeMethodExample {
	public static void main(String[] args) {
		AsyncRestTemplate asycTemp = new AsyncRestTemplate();
		String url ="http://google.com";
		HttpMethod method = HttpMethod.GET;
		Class<String> responseType = String.class;
		//create request entity using HttpHeaders
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.TEXT_PLAIN);
		HttpEntity<String> requestEntity = new HttpEntity<String>("params", headers);
		ListenableFuture<ResponseEntity<String>> future = asycTemp.exchange(url, method, requestEntity, responseType);
		try {
			//waits for the result
			ResponseEntity<String> entity = future.get();
			//prints body source code for the given URL
			System.out.println(entity.getBody());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
} 
Output
15:06:26.304 [main] DEBUG o.s.web.client.AsyncRestTemplate - Created asynchronous GET request for "http://google.com"
15:06:26.312 [main] DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [text/plain, application/json, application/*+json, */*]
15:06:26.313 [main] DEBUG o.s.web.client.RestTemplate - Writing [params] as "text/plain" using [org.springframework.http.converter.StringHttpMessageConverter@59e5ddf]
15:06:28.467 [main] DEBUG o.s.web.client.AsyncRestTemplate - Async GET request for "http://google.com" resulted in 200 (OK)
15:06:28.469 [main] DEBUG o.s.web.client.RestTemplate - Reading [java.lang.String] as "text/html;charset=ISO-8859-1" using [org.springframework.http.converter.StringHttpMessageConverter@59e5ddf]
<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en-IN"><head><meta content="/images/google_favicon_128.png" itemprop="image">
---------------------------------------- 

org.springframework.web.client.AsyncRequestCallback

AsyncRequestCallback is an interface that has a method doWithRequest() . This method needs to be defined while using AsyncRequestCallback class. In the below example we will show the use of it.

AsyncRestTemplate.execute() Example

AsyncRestTemplate.execute() executes HTTP method asynchronously. And request is driven by AsyncRequestCallback and response is driven by org.springframework.web.client.ResponseExtractor. Find the example.
ExecuteMethodExample.java
package com.concretepage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.client.AsyncClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.client.AsyncRequestCallback;
import org.springframework.web.client.AsyncRestTemplate;
import org.springframework.web.client.ResponseExtractor;
@Controller
public class ExecuteMethodExample {
	public static void main(String[] args) {
		AsyncRestTemplate asycTemp = new AsyncRestTemplate();
		String url ="http://google.com";
		HttpMethod method = HttpMethod.GET;
		//create request entity using HttpHeaders
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.TEXT_PLAIN);
		AsyncRequestCallback requestCallback = new AsyncRequestCallback (){
					@Override
					public void doWithRequest(AsyncClientHttpRequest arg0)
							throws IOException {
						System.out.println(arg0.getURI());
					}
				};
				
		ResponseExtractor<String> responseExtractor = new ResponseExtractor<String>(){
			@Override
			public String extractData(ClientHttpResponse arg0)
					throws IOException {
				return arg0.getStatusText();
			}
		};
		Map<String,String> urlVariable = new HashMap<String, String>();
		urlVariable.put("q", "Concretepage");
		ListenableFuture<String> future = asycTemp.execute(url, method, requestCallback, responseExtractor, urlVariable);
		try {
			//waits for the result
			String result = future.get();
			System.out.println(result);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
} 
Output
15:08:03.784 [main] DEBUG o.s.web.client.AsyncRestTemplate - Created asynchronous GET request for "http://google.com"
http://google.com
15:08:05.355 [main] DEBUG o.s.web.client.AsyncRestTemplate - Async GET request for "http://google.com" resulted in 200 (OK)
OK 
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us