Reactive Programming with Spring Boot | A Beginner's Guide

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so here we see that we have the data popping up one after the other each second so this is how the reactive programming is working what's going on guys welcome back to this new video in this video I'm gonna teach you all about reactive programming and I will guide you step by step to the implementation of a reactive wrist API using the most famous framework on the market today spring boot so before we start if you're new to my channel just go ahead hit the Subscribe button enable the notifications to get notified each time I publish a new video and also just take one second and hit the like button so you can help this video reach more and more people and also to satisfy the YouTube algorithm also I would like to invite you to join me on social media on LinkedIn Discord our you can also join our private Facebook group where all the community is there and everyone is helping everyone there so just go ahead and be part of this awesome community so I will leave you all the links in the description of this video down there so with no further Ado let's get started first of all let's answer the following question what is reactive programming So based on the definition reactive programming is a programming Paradigm that is focused on processing streams of data events or change as they occur so rather than than simply reacting to them after the fact reactive programming is designed to handle asynchronous and non-blocking operations making it well suited for handling real-time data and event-driven systems so this is the main thing that you need to focus on in order to understand reactive programming so in reactive programming data flows through a series of operators and functions that manipulate and transform the data as it passes through the system so the programming model is based on reactive streams which are a set of standardized interfaces that defined how data is communicated between different parts of the system so this might be a bit complicated for you so let me maybe try to simplify this definition so reactive programming is imagine having a stream of data and you have your backend or you have your service treating this amount of data so there the advantage of the reactive programming is that you don't have any blocking operations means for example imagine you have 1 000 or 1 million data to treat and then in your service each time you treat a block of data or a part of your data you can directly send it back to the front end for example or to the to the client which is consuming this this data so it's exactly like an asynchronous communication where you have your data and then you can consume it treat it apply any rules any business rules any logic on it and then each time one block of data is ready you just send it back to the customer or to the client of your rest API reactive programming has many benefits so I will I will list you some of them so first of all is the scalability so reactive programming is well suited for building scalable systems that can handle large volume of data and requests also we have responsiveness which is reactive programming can help improve the responsiveness of applications by processing data as it arrives the rather than waiting for it to be fully processed so this is what I already explained to you that you have a really high responsiveness when you implement reactive applications also residience reactive programming is designed to handle failure and errors gracefully allowing applications to continue to function even when individual components fails so it's so resilient when you implement or when you use reactive programming also reactive programming is flexible and it can be used in a wide range of applications and systems for real-time analytics and monitoring to web and mobile applications and finally reactive programming reduces complexity and it can help reduce the complexity of Code by providing a simple and consistent programming model for handling streams of data and events so yeah that was that was it about reactive programming generally speaking now let's go and let's move to the action and let me show you how we can Implement a reactive rest API using springboot so first of all let me introduce you the application or our demo application that we will Implement in this video so we will Implement a three layer application starting from the controller service and then repository but we will have some specifications to the reactive rest API so as you can see here we will have a request coming to our controller and then moving to the repository to the service before that not repository directly and then and repository and we will retrieve data from the database and when the repository will retrieve the data we will return it as a flux all right as a reactive as a stream and this stream would be passed to the service and also the service will start implementing or will start applying calculations and business rules which gonna take almost one second per per operation so for example if we have 10 records so to treat all the records it's going to take 10 seconds and I will show you how to do that also when the service is done and each time the service is done with one object or one line of of the data from the database it will also return to the front end or to the client which is our web browser in in the reactive mode so we will also we will be returning a flags and this is going to be as you can see here in the diagram so we will have a flux or we will have a stream of data and we will treat them one by one and every time each data is ready so we will send it back to the customer or to our rest API client so this is the global overview of the application that we will Implement and also you can see here this is the logo of the spring reactive and now let's move on to the next step as always the first step is creating a new spring boot project but this time it will not be a classic spring boot project but we need to make it a reactive spring boot project so just follow me on this first of all I will be using Maven for dependency management also Java as programming language and we will be using the latest stable version which is 304 at this time maybe it can be a different version in the future if you are watching this video a bit late so yeah then the the group it's going to become Dot alibu and then here I will make it reactive and the name I will just call it reactive app or reactive demo application and here the description I will make it a demo project for spring boot reactive API for example and then you see we have the package or the final package name and then we will be using jar packaging and Java 17 you can also use Java 19 if you want to now let's move on and add some dependencies so if you know me already and if you know my videos you will know that first of all I will use lombok to reduce the boilerplate code and then we will use we said that it's going to be a web API or a rest API so we will need of course Spring web right but no in this time it will be reactive web it will we need to use spring reactor web so if you search for reactive you will see here that one of the dependencies we have spring reactive web and as a description it says build reactive applications with spring web flags and Neti so let's select this one and then for the database we will before we were using the rdbc or like relational relational database connectivity but now we need to use the r2dbc so r2dbc is reactive relational database connectivity in order to process data in SQL and also retrieving data in a reactive way so just go ahead and when you use reactive web programming always think about using r2dbc all right and after that of course we will be using for example post digress as as a database or if you if you want to use MySQL or Oracle or any anything you want just go ahead and add the driver for that so we'll be using post degree SQL driver let's select it here and this is our final project so now all we need to do is just go ahead click on generate and open the project using your preferred IDE and for this video we will be using IntelliJ so now we have our project ready and open in our ntdj so I will navigate to The Source main Java and here we see that we have a classic spring boot application with the spring boot application annotation and if you run the application it will be running as always now let's start implementing our rest API so we will Implement a simple one which will be managing students so we will Implement a crowd operation to create students update read and especially the read I want this is the one I want to focus on so first of all I will start by creating a student object or a student class so I will put it into a student package and then students so the student has the following Fields so first of all a private integer ID so this is going to be the ID in the database and also private let me make this for screen private string first name and last name and then private string last name and finally let's say it has an H so private h all right so this is our student class let's go ahead and add some long book annotations so I will need I will need Getters and Setters and all arcs Constructor and also no arcs Constructor and the Builder annotation all right so my student object or student class is ready now let's move on and make it an entity so as we know like always to make a class an entity all we need to do is to add the entity annotation but oops I don't have this this annotation here so yeah when you use reactive programming you no longer have the entity annotation because we are not using uh jdbcs but it's reactive relational database connectivity so instead we have the table annotation but this time it's not from the Jakarta persistence package but it's from org spring framework data relational core and so on and so forth so you need to be really careful about that so reactive programming I want to say it again no entities so just use The annotation table and then let's give it a name for example students and this is will be our students table also when used table we have here the ID field so I will need to add the ID annotation and again it's from the same package so you also need to be careful about that when you import your annotations all right so now let's go ahead and configure the connection to our database first of all I will start by adding a new data source creating the database and then adding all the properties that we will need now let's first configure our data source in IntelliJ here you can click on database and then click on this plus did data source and then you can select the database that you are using and in this case it will be post degree SQL and then you will have all the configuration right here if you don't have the driver you will have a link here to download it otherwise if for example in this case it's telling me to switch it and then you just specify the username and password and of course if you have a different port or a different default default Port just go ahead and change it so for the username I chose username and password as password and then click on test connection so here the connection is succeeded I will click okay and then here I will just go ahead and create a new database so I will go new database and we call it spring and riscore reactive and then click ok so here you see that you have the spring reactive database I will just uncheck the other one spring reactive all right so here also go ahead and select the public schema so you can you will see all the tables and all the things that you will have in this database then let's configure the connection to our database this means that we need we will need to add properties like we like we use jdbc for example but this time we will use a different configuration first of all I will use yaml representation and then to configure the data source it will be spring and then dot r2dbc before it was spring data source username URL and so on so forth so this time it it is spring r2dbc and then URL so the URL for this connection let me show it to you right here so if you click on right click here and then you you go to properties here you will see that this is our connection or like the URL connection but this one is for jdbc I will just copy it and show you what is the difference or what you need to change here so here this is the Java database connectivity but for reactive programming it should be r2dbc so relational reactive rational database connectivity and then post degree SQL and then the URL or like the yeah the URL or the or the IP address of your uh of your database and then of course the database that you are using so here it will be spraying underscore reactive and then of course we need to specify the username which is in our case user name and then of course the password which is also password the same username and password we used for or to connect to our to our jdbc and that's it so now we have the properties to connect to our database now let's go ahead start the application and see if our table is getting created or not and let's check what will happen when we start the application now let's click and start the application so here I will just select the edit configuration and then spring Boot and reactive application click OK and then hit the Run of course we need to enable auto processing for lombok and then we will see here that the application has started and it's already starting on the port 8080. so now let's go and check our database right here I will refresh this and see if we have any tables created so here you see that we don't have a table even we have our student class right here annotated with the ID annotation for the ID and table for the class itself but the database was not created and this is because the r2dbc does not support the ddl auto or like the database creation or schema creation and tables Creations so in order to fix this what we need to do is to add a database migration tool like Flyway for example or liquibase or whatever you want to use also if you don't know about Flyway I have a video on my channel on the same playlist which is spring boot workshops and there you can learn all about Flyway migration and database operation so first of all let's go to our palm.xml file this one here and let's add the dependency so if you scroll a bit down right here and after post degree or even after lombok all you need to do is adding a new dependency and just type fly Flyway and dependency is Flyway core and also the the the group ID is org.flywaydp so for the version we don't need to specify it because it will be managed automatically by the spring framework or like the spring boot parent dependency so now we have our Flyway dependency added to our pump.xml and also to our class path so let's go ahead and create our DB migration folder in the resource folder so first of all we will create a new folder we will call it DB and enter this folder we will create in another folder called migration because this is the default folder that Flyway will look for in order to execute all the all the scripts or all the SQL scripts that we have within our application before that before we start adding the script to create the student student table let's first go to our application yaml right here and let's add the Flyway configuration so here I will add Flyway and then we have the user which is our username so the user and password should be the same as in here and also we need password which is password and also you can you can specify so here we have enabled true so by default it's true but in case you need or you want to disable Flyway you can add this property but for this time we will keep it as it is and of course we should not forget this URL right here and the URL we will paste it here but we cannot rely on this one because Flyway is automatically able to read the URL from the spring.data source and so on so forth so this is for the gdbc case but in this case we are using r2dbc so we need to change this to jdbc so Flyway uses jdbc by default and our application is a relational rest API so we need to be careful about this when use Flyway here it should be jdbc and then you keep the rest as it is and especially the database it should connect to the same database all right so now we have we have our Flyway ready now let's go ahead and add the script so for the script let's go to this DB migration folder right click and then let's create a file and we will call it V1 and then two underscores two times underscore and then init.sql for example or like you can call it create table dot SQL or whatever you want so I will make this one full screen here I don't need to change the dialect or let's let's also change it post degree SQL just to satisfy our IntelliJ so let's click OK here and now we will add the script to create our student table so the script is as follows so it's create table and then students and then parenthesis and first of all we have our ID so the ID is serial and of course it would it should be not null because because it's an ID and also we have primary key and then the next property is first name of type varchar and let's give it a length of 250. then we have last name of course also virtual and let's give it also 250 characters and then we have age which is of type integer all right so now we have the script to create our student table now we can restart the application and make sure that we have this students table created and here I just called it students because in the student class I in the table I gave it also students so you need also to be careful with that and now I will restart the application and see what will happen all right so the application is started now I will go and refresh my data source right here and see if we have the table created or not so we see that we have two tables the first one is the Flyway schema history so this is a table reserved by Flyway and this is where Flyway will put all the scripts and everything that we will be running and as you can see here it's V1 any.sql and we have the checksum and so on so forth so also as I mentioned if you need to know more about Flyway just go ahead and watch the video on my playlist also we can see that we have the student right here which is ID first name last name and age and then we have the key and we have everything ready to use so now let's move on and start implementing our application and we will start with the repository so to create a repository it's as always we will go do right click new class and then select interface and let's call it student Repository and I will show you what changed in here or what change we need to do so before we used to extend the jpa repository or the crud repository and so on so forth but in here we need to extend the reactive crud repository instead so when we use reactive programming we need to extend the reactive quad repository and of course we need to pass our entity or our model and then the type of our ID so here it's as always we have student and integer also the advantage or the thing that we can still use is the way that we write queries for example so before we used for example if we want to get all the students by first name ignore case we create a list of students and then find all by first name ignore case now it's the when when we need a list so we need to return a stream we need to return a flex all right so now let's try this so I will create a flags of type student and then I will use the same query DSL as before as we know it in Spring data jpa so it will be find all by first name for example so ignore case for example so and here all I need to pass is the string first name and that's it so this has also the same way as we do it and also if you have or if you need more methods so you know that reactive crud repository also supports the same way as we did or as we used to do with spring data jpa so our repository is ready to use now let's move on and create the service so in the same way let's go here and create a new class and let's call it student service so this student service of course we will need the spring annotation service and then I will use the required arcs Constructor from lombok 2 in order to have a default Constructor containing all the final Fields so first of all I need to inject my student repository and I will call it repository so here I will Implement few methods to find all save update and so on so forth now let's start with the find on method so the find all as a as I mentioned before we need to return a flux all right so it's public flags of type students and then let's say you find all and of course all we need to do is repository dot find all and that's it so this find on method as you can see here it's returning a flags of student and then of course we need the return and that's it so spring reactive crud repository or the the reactive Cloud repository supports all the methods that we know from before and for now we will do find all and then I will show you when we create the controller and start testing this application so I will also create a public now we want for example to find a student by ID so instead of a flux we need to use a different type which is called Mono so mono means one object and the flags means a list of objects so a mono of students and let's say find by ID and here integer ID and as always as I mentioned so we have all the methods that we need so return repository dot find by ID and then we have the ID so this is gonna return a mono or a single object of type student let's also here in the beginning let's Implement our save method so I will say a public mono of student so for example if you want you can just create and return the student and they will call it save and it will take a student as parameter and then all I need to do is my repository dot save and then student and of course I need to return the created student and that's it so you see that there is no really big changes when we Implement a reactive rest API but the changes I will you will see it just in few moments all right so for now let's stick with these three methods so we can create a student and we can find all and also we can find by ID and you also you will have all the source code in my GitHub repository and I will leave you the link in the description so you will have more methods you so you can play with all right so our repository is that our service not the repository so our service is done so let's go ahead and create our controller in the same way I will create a new class and I will call it student controller and it's since it's spring boot application so we need we will need the rest controller and also a request mapping and then I will give it slash API slash V1 slash students all right so let's now expose our resources and create the endpoints so the first one it will be it will be a post mapping and then it will return a mono as I mentioned before of students and then we will call it save so this one it will save a student and we will need a request body and an object of type student and let's call it student all right now we need to inject our repository so we will need the required RX Constructor from Lambo lombok and then let's inject our student service so private final student service let's call it service and then in here all I need to do is return service dot save and then I need to pass the student as parameter and that's it so now I will just go ahead and create my get mapping and this one is for find all and of course as we mentioned before we need to return a flags of students and let's call the method find all and then of course just return our service dot find all and the last method let's create a get mapping and then let's give it slash user ID or just an ID it's okay and then public and then mono of type students and find by ID and of course I will pass this other as a path variable and I will give it also ID here and then integer ID and finally all I need to do is service dot find by ID and I need to pass the ID as a parameter and of course let's return this so now we have our API ready to use but before that let's go ahead and insert some data into our database and let's see how this is gonna look like so now to insert some data at the start of that at the application startup all we need to do is to open our reactive demo application or the file where you have the spring boot application and then let's create a bin and let's create a public Bean of type command line Runner so this command line Runner will be executed at the beginning and here you can inject any service or any bin that you need and of course it the bin should be available um let's call it Command right now Runner and this bin should be available within your bin and also in the spring context so let's have student service right here and let's say service and then we will use the Lambda expression arcs and then like this all right so now and of course return here and now all we all we need to do is to use our service we can create a loop for to create 100 students for example and then we can insert them so I will just do this for INT I equals zero and I smaller than 100 and I plus plus and then all I need to do is my service dot save and then I will use student dot Builder dot build to build my student object so let me inline this and then so I don't need to specify the ID because it will be an auto increment and of course I need the first name so let's say it's Ali and then I will just concatenate it with the I or like this uh the counter and also last name it will be for example we can we can also use a different tool or a different Library like javafaker for example to create fake fake data but this is not the most important thing that we need to focus on and then we will need the age and let's say the age that it's I so when we run the application the application will start and it will execute this code right here so we will have 100 students into our database so let's go ahead and run the application and see what are the changes and let's then play a little bit with the reactive programming and I will also show you how the data are get how we can get the data in a reactive way so now let's run our application and check if we have our students getting created into the database or into our table or not so the application is up and running and then let's open this one right here and let's open again the table student refresh oops we don't have any data all right let's go back and check so here we are calling the save method and we are passing correctly the student object but the data is not getting created and the reason why since this save method is returning a mono right here so we need to subscribe for it so as I mentioned it's a stream event or a stream based event the reactive programming so when we when you perform an action you need to subscribe for it so you want to perform a save method but the save will not be executed it will be queued but it will not be executed until you subscribe for it so it's a publish subscribe event Paradigm so in order to fix that we need to go here into this save method and then we do subscribe so now let's restart the application and check if we have the data getting inserted into the database or not so I will check open again the student and boom now we see that we have all the information or all the data inserted into our database so that's good so far it everything is fine now let's go open our web browser and let's try the find all method because this is the most important part because just saving is fine but all we need to do like all we need to understand is getting the data because this is mainly the the stream the stream streaming data and the reactive programming so I will open my browser so in your web browser just go ahead localhost and then 8080 and then API V1 slash students and hit enter so here we see that we have all the data coming up all together because that was fast but I you will say that I already mentioned that every time the data is ready so we will send the data which is ready so let me show you how we can do this so what I will do is I will add a bit of a delay in our find all method and I will make it to be delayed for only one second or half a second or two seconds it's up to you what like the way you want to test it but here first of all we see that we have all the data here also I can display it as a row and or even a past I think it's much better so yeah here we you see that we have all the data coming from the back end but now let me show you in case you have some treatment or you have some some logic to apply which is which might take some time or for example you are Consulting different wrist API and you are waiting for the response and you don't want to block the user and you want to display the data each time the data comes so let's go back to our n3j and then let's go to our student service right here and the find all method so in this find all method I will add a delay elements and here you can see that they can pass a duration all right so here I can say duration dot off and then one second of seconds and then one second so here this means what here assuming that after finding all we are applying some mapping we are applying some some logic here to our student list and this treatment will take for example one second here now when we first when we will restart the application you will see that the data will come as a stream or in a flow each time one data is ready so it will show up in our application or in our web browser so let's click restart here yeah stop and rerun and then let's go back to our web browser and check the changes so now I will refresh this page right here and let's see the changes so here we see that we have the data is popping up one after the other each second so this is how the reactive programming is working so I added a delay and the delay we can consider it as we can consider it as some logic that we are applying or some business rules that we are that is taking some time or for example loading some images loading some data which is taking some time to be treated so in order to block the user 100 and make the user wait and the request is done so what we can do we can Implement reactive programming and then you will see that the data will show up each time a part of the data is ready for us so this is mainly it and just to recap in this video we saw how to create a reactive rest API starting from scratch from creating the spring project also adding all the dependencies you also know that spring reactive doesn't support the automatic creation of the of the schema so you need to add a database migration tool and for that I just want to remind you one last time that if you want to learn more and to know more about Flyway migration or or the Flyway tool just go ahead to my channel go to this we're spring workshops list playlist and then you will find the video alright so I hope you enjoyed this video and then I want to remind you if you're new to my channel just go ahead and subscribe and also don't forget to give me a thumbs up so we can help people reach this video or we can help even the video to reach more people and also to satisfy the YouTube algorithm it was really nice having you today so thank you so much for staying to this part and see you next time
Info
Channel: Bouali Ali
Views: 22,696
Rating: undefined out of 5
Keywords: spring, jpa, data jpa, mapping, onetoone, one to one, spring data, many to one, manytoone, class, generatedvalue, persistence, repository, service, jparepository, jpa repository, uml, class diagram, design, software, engineer, software engineer, java, jakarta, javax, spring boot, springboot, security, spring security, aliboucoding, spring boot 3.0, spring boot 3, spring 3, jwt, filter, authentication, authorization, bearer, jjwt, oauth2, github, social connect, social login
Id: EnUsNVHveyU
Channel Id: undefined
Length: 40min 31sec (2431 seconds)
Published: Mon Mar 20 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.