Spring AsyncRestTemplate


AsyncRestTemplate

  • AsyncRestTemplate gives synchronous RestTemplate via getRestOperations() method.
  • By default AsyncRestTemplate uses JDK features to enable async HTTP connection.
  • We can also use different HTTP libraries for HTTP connection like Apache HttpComponents, Netty, and OkHttp.
  • AsyncRestTemplate calls client API and gives result asynchronously.
  • Response will be in form of ListenableFuture subclass of Future.

Controller

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

	@Autowired
	private UserService userService;

	@GetMapping("/getUser/{userId}")
	@ResponseBody
	public Object getUser(@PathVariable("userId") int userId) throws Exception {
		return userService.getUser(userId);
	}

}

Service

package com.example.demo;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.client.AsyncRestTemplate;

@Service
public class UserService {

	private final AsyncRestTemplate restTemplate;

	public UserService(RestTemplateBuilder restTemplateBuilder) {
		restTemplate = new AsyncRestTemplate();
	}

	public Object getUser(int userId) throws Exception {
		ListenableFuture<ResponseEntity<Object>> future = this.restTemplate
				.getForEntity("https://jsonplaceholder.typicode.com/todos/" + userId, Object.class);
		return future.get().getBody();
	}
}

App

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootExamplesApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootExamplesApplication.class, args);
	}

}