Posted In: Spring, Spring REST

AsyncRestTemplate – Multiple Rest Calls

Usecase

1. Multiple REST services needs to be called to get all data. e.g. First service returns Name. Second service returns Address. Response needs both Name and Address
2. Both services are independent to each other.
3. Service response time is high
In these cases we could use AsyncRestTemplate.

Please note : Call to ListenableFuture..get() is sequential or will block. So call future methods only after all AsyncRestTemplate calls.

package com.example;

import org.springframework.http.ResponseEntity;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.client.AsyncRestTemplate;

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

	public void proceed() {
		System.out.println("AsyncRestTmpltExample::proceed() started");
		AsyncRestTemplate art = new AsyncRestTemplate();
		ListenableFuture<ResponseEntity<String>> lf1 = art
		        .getForEntity("http://localhost:8080/Example201726/time/30",
		                String.class);
		ListenableFuture<ResponseEntity<String>> lf2 = art
		        .getForEntity("http://localhost:8080/Example201726/time/30",
		                String.class);
		ListenableFuture<ResponseEntity<String>> lf3 = art
		        .getForEntity("http://localhost:8080/Example201726/time/30",
		                String.class);
		ListenableFuture<ResponseEntity<String>> lf4 = art
		        .getForEntity("http://localhost:8080/Example201726/time/30",
		                String.class);
		try {
			ResponseEntity<String> entity1 = lf1.get();
			System.out.println(entity1.getBody());
			ResponseEntity<String> entity2 = lf2.get();
			System.out.println(entity2.getBody());
			ResponseEntity<String> entity3 = lf3.get();
			System.out.println(entity3.getBody());
			ResponseEntity<String> entity4 = lf4.get();
			System.out.println(entity4.getBody());
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("AsyncRestTmpltExample::proceed() ends");
	}
}

Tags:

by , on July 18th, 2017

  • Categories