Spring Boot | Exploring Asynchronous 🚀 Calls with @Async Annotation | JavaTechie

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone welcome to javat so today we are diving into a powerful feature of spring boot that can significantly enhance the performance of your application asynchronous calls using The async annotation okay all right if you have ever wondered how to boost the performance of your springboard application or make certain task run in the background then you are in the right place so without any further delay let's get started [Music] so before we jump into the code let's quickly understand the importance of Asing feature in Spring boot so let me walk you through a realtime use case I assume everyone has used an e-commerce application to place an order but do you know how the entire order fulfillment functionality works and what steps are involved in the processing a single order no worries let me give you a high level overview of this order fulfillment process to demonstrate the async use case Okay so if You observe I have considered few Services here once an order request comes in the purchase order service will check with the inventory service for product availability if the product is available it will proceed with the payment process after completing the payment it will notify to the user about the order and payment next the order is assigned to a vendor the vendor picks the order items from the warehouse and package them securely after packaging the order it will assign to the delivery partner okay so the delivery partner is responsible for transporting the orders from the vendor's Warehouse to the customer's address next following the this the delivery partner assign a trailer and dispatches the order to the customer address so this entire process is known as the order fulfillment process okay so just keep in in mind that what I have explained in this presentation is just a high level overview in real time it usually involves numerous steps so don't consider this flow as the source of Truth for demo purpose I have selected a few known services that will help us to sync with the concept okay so to complete the order fulfillment process we need to go through many steps which could be time consuming in real time each of them could be a microservice as you know in the microservice world each service need to communicate with others either to get a response back or to send the input so if You observe in this workflow the purchase order is the one micros service that needs to call other service to complete the order fulfillment process since the order service needs to make HTTP call to the others each service will definitely take take some time to respond let's consider some random response time it can be less or more so just assume this number okay now if You observe the overall service call took 8 hours or more that is expected right as it needs to go through so many steps now the question here will my user wait for 8 hours to just get the response saying that okay your order has been placed definitely not if that's the case no one will use this kind of E Commerce application then what is the solution how can I convince my user it's very simple once the payment process is done immediately give a response back to the user with some tracking ID or transaction ID let the rest of the flow execute in the background okay in asynchronously since you have shared the tracking ID or transaction ID with the user they can happily track their order to get the updates whether the order has been dispatched or what what is the state of of the order okay but how can I design the asynchronous process that's where the spring boot provided at the rate async annotation to deal with such kind of scenario so until the payment processing you can make the synchronous call rest all the services like notification packaging assign the vendor assign the delivery partner dispar the product all rest of the services you can perform or you can execute them in the background using asynchronously okay that is the that is the scenario where you can use The atate assing annotation given by Spring boot that's awesome isn't it so let's get our hands D with the Asing concept with the same use case so let's go back to our ID to demonstrate this particular code so to save our time I have created a small PC I'll walk you through the code then we'll understand how we can enable the async in Spring boot so let's go to the p. XML so the version of spring boot I'm using 3.1.5 and I just added the web dependency and lombok dependency okay nothing else fine now let's go to the service so I have created a service called order fulfillment service and if I'll expand this for you you can clearly see the steps what I have discussed in the presentation right inventory service process the payment notification service assign the vendor packaging assign the delivery partner dispar the product and assign the trailer okay okay these are the steps so just what I have done here I have created a method called process order so something I'm setting the tracking ID in the order response okay because I'm using the same as a input and response so I have set the tracking ID then simple step as for the presentation this purchase order first check with the inventory service then if the product is found then it will just process with the payment okay so if If You observe in the code what I'm checking if the product is available in the inventory service so I don't I didn't write any logic I have just written the true and false okay so rather than writing these services in the same project this should be a separate micros service since for the demo purpose I'm just writing it here only okay but to understand the ASN flow in real time you could create a separate service called inventory service and you can write the actual logic here I'm just returning true because this is the demo I want to show you the asynchronous call in this particular workflow so that's fine so always it will give you the true so once the product is available in the inventory service then we are processing the payment so if You observe again in the payment service I have written the process payment method this I have created a separate service but in the micros service it need to be a separate micros service okay and here I don't don't have any logic just added the log statement and the process payment might take some time so intentionally I am blocking the thread for 2 millisecond okay so this there you should write the actual code not this one so since it is the demo to make it easy for you I have just defined different service fine so if product is available then process the payment else throw some exception that's fine this is what I want to execute in synchronus okay so if you understand the workflow correctly if I will show you the presentation purchase order inventory service payment service these three interaction I want to perform synchronously so that immediately after the payment is done I can send the response back to the user okay and this notification and other services I want to run in the background so I have written the other services as well okay so again I have written this as a method you can create a separate micro service called notification service and you can write this notify user by email or SMS you can write that actual logic so here I have just defined the method notify the user see very simple guys each and every Services I have defined as a method here fine notify the user and it will block the thread for 4 millisecond and notify the user then assign the vendor I have added the log stat then packaging assign the delivery partner assign trailer and dispatch all the steps what we have discussed in the presentation will be in the same flow okay now what I'm doing I just call this process order method from the controller class if I will expand this all the services we are calling from the controller process the order then notify the user assign vendor packaging delivery partner assign the trailer and dispat everything I'm just doing here okay but what is our goal to do up to this process order I want to execute it in synchronous mode and rest all the services I want to run in asynchronous mode fine so how I can perform that so I will tell you in a moment but before that first let's check the default Behavior without implementing the asynchronous call how this particular flow is behaving okay so simply I will start the application there is no other logic guys okay I have created this service then dto that is order and controller so this is the simple steps for the demo purpose I have just written the sopn statement so let's wait it to complete yeah it started now let's go to the postman what I'll do I will just minimize this so that you can see the response in the console now now let me trigger the request okay I need to keep this side can you see here initiate the payment for order complete payment for the order then notified to the user each and every steps is getting executed but we are not getting the response because my entire main thread is blocked to complete this process still we are implementing not implementing still we are using the synchronous flow here can you see here whatever the thread blocking we have added thread. slip it is taking Tak that much time to complete the task and then we are getting the response it took 26.4 n second okay now if I trigger again it will initiate the payment for the order this then again it will take time to complete all the steps then we are sending response to the user if that is the case then it's not a good practice to implement right because this notification service or assign vendor service packaging service will definitely take some time and if You observe the entire flow is executing with the single thread that is the main thread can you see here hdtp nio 9191 ex EC3 all the steps or all the flow is executing by the single thread and it's blocking the main thread that is not the good practice to implement if you have such complex scenario then what we can do so as we understand in the presentation let's make this purchase order inventory payment service by default synchronous and rest all the service I want it to be execute in the background without blocking my main thread let them initiate a separate thread and let them execute in the background okay how I can do that very simple that is the reason we need this async annotation given by Spring boot so we'll go step by step to understand how we can enable the asynchronous flow here okay so the first step we need to create our own thread pool okay because I don't want my flow to block the main thread by executing in a single thread so I need to create my custom thread pool task executor if I if I will not create that then by default if you enable the async in your spring board by default spring boot will create simple async task executor okay with the default configuration now you have the option to create your own threadpool task executor by defining what is the number of core you want to use what is your Q capacity how long your task can be present in the queue what is the max pool size lot of things you can customize as per your use case so rather than relaying on the default task executor given by the spring board let's create our own threadpool task executor okay so that we can play with the thread so for that what I can do I'll just create a class here inside this config package let's name it async task executor or async configuration just annoted this at theate configuration then simply just create a bin of executor by creating the thread pull task executor object it's very simple step public executor then simply Define a method something like as sync task executor or something like that then just create the object of threadpool task executor fine now in this task executor you can Define the core pool size Q capacity or Max pool size those many things okay so let's write task executor dot set core pool size here I am setting the core pool size to the four these threads are kept alive even when they they are ideal okay now I'll just Define task executor do set Q capacity I'll just Define the Q capacity to 150 so what it will does it will set the maximum number of task that can be held in the Q if the Q is full and additional task are submitted let's say Q is full with the 150 and 151 task came then it will trigger the creation of the new thread up to the maximum pool size you will Define okay task executor do set maximum pool size so I'll Define it to the four so what this Max pool size does it sets the maximum number of thread that the pool can have if the Q is full and the maximum number of thread has been reached so we have defined the four right if there are so many task which is not splitted by this four thread then those additional task will be rejected okay so these three are the key key configuration for concurrent execution so you need to Define based on your core pool size of the BM okay that's fine now just Define some prefix task executor do set prefix something like that set thread name prefix okay I'll Define something like async task thread so that this will be act as a prefix once you have done with this then you just need to initialize your task executor task executor do initialize then just return it and just Define this as a at theate bin and you can Define your name of your bin something like async task executor just copy this I just want to Define my B name this is optional okay but I want to Define this B name so that I can tell to my spring what all method can be used this particular configuration to execute ASN ously okay next we need to tell to the springboard that please enable the asynchronous method execution for me so for that there is annotation given by springboard enable as sync we can use this annotation to enable the asynchronous method execution so once you have written this particular annotation spring boot will internally search on top of what method we have annotation called atate asnc those methods only spring boot will execute asynchronously so I will show you that how you can Define that annotation as well let's go to the order fulfillment service so this particular as for the flow purchase order inventory service and payment service this flow I want to make synchronous call so I am not going to modify these three services okay only rest of the services I want it to be execut in asynchronously so we have enabled the enable Asing to tell to the spring board please enable ASN must call for method for which method wherever you are finding this annotation at the async okay and Define what thread configuration it will use that is what the bin we have defined fine now rest all the method I want it to execute asynchronously I'll just Define this once you added atate enable as sync annotation then spring boot will look for this particular annotation on top of the method and make make sure wherever you have added this at theate async annotation that method return type either viid or completable future I cannot keep string here okay even though if I Define it will give the exception so always it will be either void or completable future so if you have multiple task and you want to join all the task thread result and return it back to the user then you can go for the completable future for now since this is the demo I have just defined void because we just want to understand the concurrent flow okay and we'll verify which thread is getting executed each and every flow fine so we we are done with the configuration now what will do we'll just test the application so what we are going to verify once the payment is done it will notify to the user so until the payment is completed it will immediately give the response back my thread will not block to execute all the flow okay that is what something the purpose of using as synchronus right once the payment is done immediately I want to give the response back to the user and rest all the flow will be execute in the asynchronous I mean with a different thread rather than blocking my main thread that is what we are going to prove now that's fine let me start the application and I will just minimize little bit so that we can see the proper con cons so it started let me clear this now from the postman I will trigger just observe here in the console when the payment process is done immediately user will get the response okay with the tracking ID now let the other process will execute asynchronously with the different thread that is what the goal I want to demonstrate here so let's run it initiate the payment see here immediately we got the response once the payment is completed okay next it started executing other flow order packaging completed notified to the user it's running in the background right and you can see it is using the different thread task executor thread three for packaging thread one for notification service thread two for assigning the trailer trailer okay assigning the vendor right and then three for assigning the trailer and four four for delivery partner so we have defined the four thread and all the four thread is executing behind the scene without blocking my main thread okay so let me retry again so that it will be clearly visible just keep a eye on the console once the payment is done it is not waiting all the steps to complete and giving the response once the payment is done immediately we are getting the response back since all the rest other flow we make it asynchronous so it's running background okay so let me run it again see here we got the response then other steps are getting executed in the background with the different thread okay that is what something the asynchronous flow you can achieve in the microservice world by implementing this at the rate async annotation so I hope the use case what we have discussed here is the correct scenario to cover the async and I hope you are clear with this particular use case and its implementation to understand the asynchronous flow okay so do let me know in the comment section if you guys have any doubts and you can give a try with different use case okay that's all about this particular video guys thanks for watching this video meet you soon with A New Concept
Info
Channel: Java Techie
Views: 43,892
Rating: undefined out of 5
Keywords:
Id: R_gejlOXR7g
Channel Id: undefined
Length: 21min 25sec (1285 seconds)
Published: Fri Nov 17 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.