Spring Boot Application Events Explained with Real-Time Examples | @Javatechie

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone welcome to Javi in today's microservice world many of you may have heard of event driven architecture this architecture allow one microservices to communicate with other in a synchronous manner right so if you consider below example I have an order service and one restaurant service when the order service receive an order it immediately publish an event to the restaurant service using capka as a message ing channel the restaurant service then consume that event from the capka and prepare the food and send a notification to the end user in this scenario these two micros service communicate with each other but the order service does not need to wait for a response from the restaurant service this is why it is called asynchronous communication between the microservices right so this event driven architecture is useful for inter microservice communication but what if we want to implement events within a single microservices or you can say what if I want to implement the events for inter application communication I mean I just want to event within the order service or I just want to implement the events for restaurant service then how we can achieve that that is where these spring events came into the picture okay so using this spring event mechanism you can publish the event within the within inside the application okay don't worry I'll give you an example to make it easier to understand so let's consider another use case I'm working on a healthcare project where I just want to design a feature called patient discharge so if you think practically before discharge a patient what all action or what all activity we usually perform okay let's list down couple of key point then we'll try to understand how spring events help us to solve this problem now to discharge a patient first we need to finalize the patient bill then once we finalize the patient bill then we need to update the patient medical records or history correct now once we update that then also we need to assign the room to the next patient fine so if all are done then we need to send a discharge notification to the patient and all the relevant medical staff okay so these are the steps or action we need to perform to just Implement discharge patient feature now if You observe I have four different kind of action so for billing I will create a billing service to update the patient records I will create a record service similarly I will create for cleanup and assign the room to the new patient I will create a service called housekeeping service and for notification I will create notification service now if you'll Design This Theory into the code it will something look like this right I have a discharge service and I have a method called discharge inside that I'm just in Booking each and every services and their methods right so this looks good then what is the problem with this particular approach let's discuss those problems one by one okay so the first problem is tight coupling If You observe this discharge service is tightly coupled with all other services billing service Record Service notification and housekeeping service this means any change in the API or behavior of these Services could require changes in the discharge service okay so this is one of the key problem if you'll go with this particular approach now let's discuss the second problem that is difficult to extend so adding a new service to handle additional task upon patient discharge would require changes to the discharge service directly okay this is another problem which violate the open close principle of solid design pattern okay now the third drawback is testing and maintenance testing becomes more challenging because we need to mock or stop multiple services and their dependency it also increase the maintenance overhead since the discharge logic is not modular because we Club everything in a single class which is not modular fine now next drawback is lack of async process so if You observe all service calls are executed in a synchronous manner or you can say in a sequence way if any service takes a long time to execute it can delay the entire discharge method okay so for example let's say billing service is taking more time to execute then this update medical record notify clean up these methods will not execute until it completed the building service method okay so this is one of the drawback that we are not making it a sync rather we we are going with the synchronous flow okay so we have these are the drawbacks if you follow this particular architecture now then how we can make it better so to do that let's remove this dependency and make our implementation lose coupling now you might ask me hey if we remove the service dependency then how can we perform these operation like billing operation notification operation update the medical record how can we do that because because from the discharge method or because from the discharge service we are not pointing them to execute then how my code will work right that is what the challenging task so to solve this kind of problem we have the spring events so what we'll do we'll simply publish the discharge event from the discharge method now whoever service want to use that event they can simply listen to that event and process their task accordingly so if You observe here discharge method act as a publisher who publish the events and all other services who listen to that event will be act as my listener so what we are doing here rather than invoke the service by tightly coupled them with my discharge service rather I simply publish an event from the discharge service now whoever service want to execute or whoever service want to take that event and process they can simply listen to that event and execute their job okay so in this way we can design our application better using spring events mechanism to avoid the discuss problem like tight coupling difficult to extend testing and maintenance and lack of assing process okay so we need to play with the events to make our application lose coupling and to design it more efficient fine so let's do a handsome example to understand the same scenario in action using spring events so without any further delay let's get [Music] started so let's go to our intelligent idea I have created the skeleton with the same scenario what we have discussed in the presentation now let's begin with the pom.xml If You observe here we are using the latest version of springboard which is 3.3.0 and we only added the web dependency and lbook dependency okay there are no additional dependency added in this project let's close it now to deal with the different service billing housekeeping medical record notification I have created different services say okay you can see here now I have defined a controller class with one end point to process the paent discharge and this is the post mapping you can see here this is the what request I'm sending from the postman correct now if You observe here from this controller I call the pent discharge service if you go here you can see right this is the patient discharge service and it tightly coupled with all other services billing service medical record service housekeeping and notification service now if You observe in the discharge paent method we are in Booking each and every Services okay this is what the tightly coupling approach and we also understand there are couple of drawback like if You observe here it's difficult to extend testing and maintenance and lack of async process so that is what is the problem in this approach now what you understand if you understand here from this discharge method rather than in Booking the service just publish an event okay so try to picturize this particular image on your mind so that it will help you to design your spring event based implementation okay so rather than invoke the services from the this discharge method what we want to do we want to publish a event so go to the code just remove this top because we don't want this tight coupling approach just comment it for now here also I'll just remove it fine now then from this discharge paent method how can I perform this activity billing medical notification and housekeeping so just publish an event so that these Services building medical housekeeping and notification that is what we have defined in the Handler package they will listen to that event and they will process accordingly okay now what is the first step publish an event so to publish an event first I need to create a event which is which is kind of generic right so what I'll do I'll create another package e then simply create a class Java class I'll name it pent discharge event now to play with the spring event saying that okay this is what the event class I created you need to extend that from application event okay once you extended from application event it will ask you to define the Constructor so in this particular patient discharge event I also want to as part of this particular event I also want to populate the patient idea and paent name so just Define those two field then just pass them as part of Constructor then initialize it fine now also Define the data annotation if you don't okay if you will Define the data annotation it will expect a default Constructor so Define getter and Setter fine now this is what the event will be published to other services okay I'm going to publish this patient discharge event now whoever service want to perform the task just consume that or just listen to that event and do your logic or execute your logic okay so this is the event right so you have created this event if you understand the presentation we have created the first step that is event now next we need to publish that event right so how we can publish that from this discharge service if will go to the discharge service code to publish the event from a service we can use the class application event publisher that class is provided by the spring framework so what you can do I can use the class private application event publisher then just inject it fine now using this event publisher we can publish this pent discharge event now whoever the service want to use that they can simply listen to that event and process the logic so it's straightforward okay so what you can do go to the disar service we know we know need this approach let it be now what I want to do here I want to publish that event event publisher dot publish the event can you see here and publish the event application event so if You observe here this event we extend from application event correct so just pass it here new patient discharge Event Source is nothing your current object and give the patient ID and patient name because these two value we have defined in our Constructor so let me format it so if You observe we just publish the pent discharge event now how these Services building service housekeeping medical record notification service we listen to that event it's straightforward go to that particular class then simply there is a annotation first of all you need to tell them which event they want to consume so in your application you might have 10 event right so this building service Handler which event he want to consume so just pass that event name okay patient discharge event then how can he consume that event or listen to that event so there is ation called event listener okay like in capka we have capka listener in other rabbit mq or active mq we have the corresponding listener similarly for spring event you can use at theate event listener annotation and you can specify which events you want to listen in this particular method fine so just add it I mean just modify the sis out statement will for patient patient ID now same way we need to configure in other service to listen to that particular event so go to the other services go to the medical record service let me Zoom this for you then just Define patient discharge event you can Define any variable name fine that's fine okay cool now here you need to annoted at theate event listener then here also let me map the patient ID similarly just go to the other service housekeeping service just annoted here at theate event listener paent discharge event preparing for the for next patient after discharge off give the patient name fine now go to the last one notification service here also Define which type of event this method will listen to uh patient discharge event just annoted at theate event listener so the approach is same whether you have a single service who want to listen or 100 service who want to listen just annoted and specify which event you want to listen in this particular method okay now just here sending discharge notification for patient just just add some meaningful statement okay so I'll will just add event. getet paent name that's it so I believe we are good now if you to go to the presentation from this discharge service we publish the event using application event publisher then we have these are the services who listen to that event using at theate event listener annotation right this is what we have implemented to just demonstrate spring events mechanism now we are good let's run our app and we'll see the result okay just go to the intellig go to your main class simply run it so you can see here it started on port 8080 all good let me clear this now I just need to trigger this end point right discharge hyen API then process and I need to give this request so I have that payload in Postman so just let me send the request click on send so we got the messages now if you see here can you see here we have not invoked the buing service manually we have commented out or I believe we have removed it go to the discharge service see here we have commented it right but still the event is getting published to whom billing service and billing service logic is is getting printed here can you see here finalizing billing for paent this then housekeeping service preparing room for the next patient after discharge of this particular user medical record service notification service can you see here so I have added two log statement patient discharge process initiated then these are the event published to these Services they executed the next then at the end we got the last statement I mean the patient discharge process completed But If You observe here see here the first initiate initiate statement then finish statement inside that it is getting executed I mean wherever it publish the event those corresponding service are executing their logic But If You observe here still we didn't achieve the async Flow by default this event listener will not give you option to make it a sync so what it will does see here if you see here let me Zoom this yeah now here even listener are by default synchronous in Spring boot or spring framework the publish event this particular event method blocks until all listener have finished processing the event okay so that that's what we observe in the statement right this publish event method will block till all its listener is executed okay but that that is not the solution we want right that's fine we are performing the event driven architecture within the same application using spring event but I want to make it as syn how can I do that that's very simple because you already aware about how to play with async or how you can make a API async using spring async annotation right so that is the simple statement you can just add it to make it a sync so what what we can do just go to The Listener class or your other services simply just annoted here async and also you need to enable async now in building service we have defined right this annotation to validate whether it really those events are getting executed in different thread or not what I'll do I'll just add a statement I'll just print the current thread thread do current thread. getet name fine let me copy this go to other services let's go to the housekeeping and just annoted here or you can add here also as sync then just change the statement here I just want to validate that all my listener is being executed in different thread that is what my main intention to achieve the as sync okay now go to the medical record service Handler just annoted here at theate async and I will just openend the messages I mean the thread name then the last one notification service make it a sync so now this will not be synchronous rather it will be a sync okay so let's verify that let me run our app so it started now let me clear this go to the postman and let me send the request again now if you see here see here first the loog statement discharge process initiated for the user then billing service housekeeping medical record then you find the last statement of your discharge process completed then your listener see the flow of execution it's random right it's not a synchronous this is the listener one listener 2 listener 3 then you find some find log statement from your code then again it executing the fourth listener okay so if You observe here this is what your thread name task one task 2 task three task 4 so the thread is created with this particular name the Reason by default spring use a simple async task executor for executing the task in assing mode which create a new thread with this name task one 2 3 4 4 now if I'll rerun again the thread name will be like 5 6 7 8 like that okay let let's see that let's run it again now see here the order of execution billing service execute in different thread task pip housekeeping medical notification is executing in different different thread and now if you see here you find the log statement then in ASN asynchronously it execute these events or The Listener then you find the log statement now let me rerun it see this task is being picked by 13 14 6 and 13 so the moral here I'm trying to convince that each listener task will be execute in a different thread if you will run it in a async mode but if you'll run it in a synchronously then it all will be run in single thread okay so but the main thing we understand that how we can play with the spring events okay rather than hard Cod the services in paent discharge service like this we simply publish the event and all our listener listen to that event and they execute their job okay so this way we can avoid all the issue we have discussed like tight coupling difficult to extend testing and maintenance and we can achieve the asynchronous flow using this spring events mechanism okay so again this will be helpful for in service communication okay if you have two different application or two different system or to different micros service then you can go for the capka because that will be inter micros service communication but if you want to play with the event within a application then you can happily use this spring events and I have already explained in in details way how we can play with the events with different Services okay so I hope this will be helpful for you do let me know in a comment section if you guys have any doubts 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: 18,668
Rating: undefined out of 5
Keywords: Spring Boot, Spring Boot Events, Event-Driven Architecture, Spring Boot Tutorial, Java Spring Boot, Spring Boot Example, Asynchronous Communication, Spring Framework, Custom Event Listeners, Real-Time Example, Spring Boot Beginners, Spring Boot 2024, Spring Boot Coding, Java Programming, Spring Boot Development, javatechie
Id: imF5ja5OkAo
Channel Id: undefined
Length: 27min 26sec (1646 seconds)
Published: Fri May 31 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.