Posted In: Spring, Spring REST

AsyncRestTemplate – Rest call with ResponseExtractor, AsyncRequestCallback

Usecase

Your application calls rest service which takes some time to complete. You need to respond to the client with received message immediately. Once you receive the response do some action.

package com.example;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.AsyncClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.client.AsyncRequestCallback;
import org.springframework.web.client.AsyncRestTemplate;
import org.springframework.web.client.ResponseExtractor;

public class AsyncRestTmpltExecute {
	public static void main(String[] args) {
		new AsyncRestTmpltExecute().proceed();
	}

	public void proceed() {
		System.out.println(
		        "AsyncRestTmpltExecute::proceed() started");
		AsyncRestTemplate art = new AsyncRestTemplate();

		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 response)
			        throws IOException {
				return IOUtils.toString(response.getBody());
			}
		};

		Map<String, String> urlVariable = new HashMap<String, String>();

		ListenableFuture<String> future = art.execute(
		        "http://localhost:8080/Example201726/time/30",
		        HttpMethod.GET, requestCallback,
		        responseExtractor, urlVariable);

		try {
			System.out.println(future.get());
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println(
		        "AsyncRestTmpltExecute::proceed() ends");

	}
}

Tags:

by , on July 20th, 2017

  • Categories