Posted In: Spring, Spring REST

AsyncRestTemplate – Callback

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 org.springframework.http.ResponseEntity;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.client.AsyncRestTemplate;

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

	public void proceed() {
		System.out.println(
		        "AsyncRestTmpltCallBack::proceed() started");
		AsyncRestTemplate art = new AsyncRestTemplate();
		ListenableFuture<ResponseEntity<String>> lf1 = art
		        .getForEntity(
		                "http://localhost:8080/Example201726/time/30",
		                String.class);

		lf1.addCallback(
		        new ListenableFutureCallback<ResponseEntity<String>>() {
			        @Override
			        public void onSuccess(
			                ResponseEntity<String> result) {
				        System.out.println(result.getBody());
			        }

			        @Override
			        public void onFailure(Throwable t) {
				        t.printStackTrace();
			        }
		        });
		System.out.println(
		        "AsyncRestTmpltCallBack::proceed() ends");
	}
}

OUTPUT – Body printed after Callback

AsyncRestTmpltCallBack::proceed() started
AsyncRestTmpltCallBack::proceed() ends
{'success': 1500456789979}

Tags:

by , on July 19th, 2017

  • Categories