DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • How to Introduce a New API Quickly Using Micronaut
  • Building a Real-Time Audio Transcription System With OpenAI’s Realtime API
  • Efficient API Communication With Spring WebClient
  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD

Trending

  • Implementing Explainable AI in CRM Using Stream Processing
  • Securing the Future: Best Practices for Privacy and Data Governance in LLMOps
  • Cloud Security and Privacy: Best Practices to Mitigate the Risks
  • How to Build Real-Time BI Systems: Architecture, Code, and Best Practices
  1. DZone
  2. Data Engineering
  3. Databases
  4. Asynchronous API Calls: Spring Boot, Feign, and Spring @Async

Asynchronous API Calls: Spring Boot, Feign, and Spring @Async

Learn how to make asynchronous API calls from Spring Boot using Spring Cloud OpenFeign and Spring @Async to reduce the response time to that of a one-page call.

By 
Mukut Bhattacharjee user avatar
Mukut Bhattacharjee
·
Updated Sep. 28, 22 · Code Snippet
Likes (6)
Comment
Save
Tweet
Share
30.6K Views

Join the DZone community and get the full member experience.

Join For Free

The requirement was to hit an eternal web endpoint and fetch some data and apply some logic to it, but the external API was super slow and the response time grew linearly with the number of records fetched. This called for the need to parallelize the entire API call in chunks/pages and aggregate the data.

Our synchronous FeignClient:

Java
 
@FeignClient(url = "${external.resource.base}", name = "external")
public interface ExternalFeignClient {

    @GetMapping(value = "${external.resource.records}", produces = "application/json")
    ResponseWrapper<Record> getRecords(@RequestHeader Map<String, String> header,
                                            @RequestParam Map<String, String> queryMap,
                                            @RequestParam("limit") Integer limit,
                                            @RequestParam("offset") Integer offset);


}


Let's prepare the configuration for the async framework:

Java
 
@EnableAsync
@Configuration
public class AsyncConfig {
 
	@Bean
	public Executor taskExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(5); // set the core pool size
		executor.setMaxPoolSize(10); // max pool size
		executor.setThreadNamePrefix("ext-async-"); // give an optional name to your threads
		executor.initialize();
		return executor;
	}
  
}  


Now to make the feign clients work in asynchronous mode, we need to wrap them with an async wrapper returning a CompletableFuture.

Java
 
@Service
public class ExternalFeignClientAsync {
  
	@Awtowired
	private ExternalFeignClient externalFeignClient;

	@Async
	CompletableFuture<ResponseWrapper<Record>> getRecordsAsync(Map<String, String> header,
                                            Map<String, String> header,
                                            Integer limit,
                                            Integer offset){
		CompletableFuture.completedFuture(externalFeignClient.getRecords(header,header,limit,offset));
	}

}


Now our async feign client is ready with a paginating option using the limit and offset. Let's suppose we know or we figure out by some means (out of scope for this article), the total number of records available. We can then consider a page size for each call and figure out how many API calls we need to make and fire them in parallel.

Java
 
@Service
public class ExternalService {
  
  @Autowired
  private ExternalFeignClientAsync externalFeignClientAsync;
  
  List<Record> getAllRecords(){
    
    final AtomicInteger offset = new AtomicInteger();
    int pageSize = properties.getPageSize(); // set this as you wish
    int batches = (totalCount / pageSize) + (totalCount % pageSize > 0 ? 1 : 0);
    return IntStream.range(0, batches)
                    .parallel()
                    .mapToObj(i -> {
                        final int os = offset.getAndAdd(pageSize);
                        return externalFeignClientAsync.getRecordsAsync(requestHeader, queryMap, fetchSize, os);
                    })
                    .map(CompletableFuture::join)
                    .map(ResponseWrapper::getItems)
                    .flatMap(List::stream)
                    .toList();
  }
}
  


And voila!

The entire API call is now broken down into pages and fired asynchronously, with the overall response time reduced to the time taken by a one-page call.

API

Opinions expressed by DZone contributors are their own.

Related

  • How to Introduce a New API Quickly Using Micronaut
  • Building a Real-Time Audio Transcription System With OpenAI’s Realtime API
  • Efficient API Communication With Spring WebClient
  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!