NestJS Microservices - 2 - Using TCP

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to part two of microservices in SGS in part one we talked about micro services but only at a conceptual level in this video we're going to dive into the code and actually build our first micro service but before we do that let's take a quick look at one more slide and talk about what we're going to build before we switch over to vs code I'm going to do things a little different for this video instead of starting from scratch we're gonna start with an example of a traditional app it'll be super simple just a controller with a single method that injects a service that also has just a single method for this example our service will be a math service that simply sums the elements of an array and returns that result we will review the code for this example and then we're gonna recreate this example as a micro service using basic TCP as the transport this will involve creating two Ness projects one for the web app and the other for the micro service simple enough right I promise you it is let's jump to the code and I'll show you what to do now this is our starting point if you look here in the source folder of this traditional app we just have four files the entry point is main TS where the app is bootstrapped when it's bootstrapped the app module is passed to it and the app module contains references to the controller and service so let's review these files individually in that order here's our bootstrap this is basically the bootstrap I believe that you get when you start a new nest project I don't believe I've made any changes here so you define a bootstrap function and then you immediately call that and in this bootstrap function we are instantiating a nest app and we're passing it the app module and then we're as in any standard web server config here we're just calling apt listen and passing the port we'd like for it to listen to so next stop is the app module we got module here this is where we define our imports controllers providers standard nest stuff I hope you're familiar with in this case we have one controller and one service that we plan to inject in that controller therefore we put it in our fighters so let's take a look at the controller pretty standard we just annotate it with a controller I've been standing a logger so I can lock some messages in the constructor we're doing constructor injection and injecting that math service we have one method which is mapped to the a drought and the method that's called on this a drought is down here and all we're simply doing is we're just there's going to be passed a array of numbers in the data field so I'm going to log the numbers that we're adding and then we're gonna call the math service the accumulate method on the math service and pass in this array of numbers so last stop if we look at the math service we have an injectable class that's a service here we're taking this number and then we're just saying hey if it's you know it's null let's just make this an array so that you know no type errors when we call reduce and add up those numbers in the array pass it back based on this if we look back at our controller if we make a post request to the a drought and pass it an array of a few numbers then it should add those numbers and return it back now to check this we're gonna go into insomnia this is very much like postman and you can use postman if you'd like however insomnia natively supports graph QL queries so I like to use it a lot instead in our local host for 3000 as we set up in main TS I'm just gonna pick a post to this a drought and here I'm gonna make a form URL encoded request request and I'm gonna use this format in order to pass an array so passing five three and four should give us eight twelve should we should get the number twelve back when we send this let's give it a shot and it couldn't connect to server' perhaps I should start the server okay we're good to go let's try this once more and sure enough we got 12 and since we added some logging in the controller right here we can see that yes it says adding five three and four and it returned 12 so that is our starting point from here let's move on to actually recreating this exact same thing but in a microservices architecture where we pull out the math service and have two projects one project for the web app and one project for the Micra service and this web app uses we just reviewed the code for our example traditional app you see at the top here because so few changes are required to convert this to a micro services app I think the best approach is to simply make a copy of this project and modify it to our needs in order to convert it into a micro service I'm gonna actually make the copy twice one for the you know the client project and one for the micro service project so for the client project what we'll be doing is simply removing that math service because it's going to be extracted and adding in the client code to contact the micro service in the micro service itself we'll be setting up the the necessary changes in the controller and in the main TS file to be serving data as a micro service rather than a standard HTTP so let's get started there let's make those copies and make those necessary changes the first thing we want to do is to add an STS micro services if that was very quick so with that added we're going to have to make a few changes here not much the app module will stay the same the math service will stay the same we just need to make some small modifications in the controller and change the bootstrap code in our main TS so let's start with a controller first thing I want to do is import message pattern from SGS micro-services there we go and this post instead of like with an HTTP service you know using the post decorator we're gonna use this message pattern decorator we're just gonna look pretty much the same we're gonna just call it add if you look in the NIST GS Docs they actually pass an object here it looks something like command ad or something like that but it means it can be whatever you want keep it simple I'm just gonna leave it as add just like it wasn't our post I'm gonna remove this body information that's specific to HTTP and let me take a quick look at this yeah I think that's all we really had to do right and so here I'll just say fine message pattern for this method and what will happen is when this is called the biker service is called with this message pattern this is how it wraps to the controller right it takes that message pattern and we're defining here with this decorator that whenever you receive this message pattern this is the method that you should execute next we're gonna go to our main TS file in here we're also going to have to do a few imports actually we have to change this up a bit so why don't we just start by deleting this code there we go I want to see let's make a lager lager and I'll show you what I'm going to do with that in just a moment so let's actually annotate this a lager instance and then down in here in the bootstrap what we're going to do is we're going to do similar that we did before we want to instantiate the the nest bat with nest Factory the only difference is we're going to use the create micro service instead of create we're gonna pass the app module and we're also going to pass it a micro-services options object that will define here in just a moment to just ignore that error for not having that yet now with HTTP you do something like app listen but we're not gonna do that and define the port there because the ports going to be defined in that microservices options so really all we have to do here is tell it to listen and then instead of giving a port number we're going to give a callback over who want to execute some code in this case I'm going to just say log log my first service is listening so we can see that the log file and know that that's working so at this point we just need to create that that options object right grade the microservice options well if I could type today those options equals and then first thing most important but the transport is so let's say transport yeah import from micro-services TCP and then the options will be the host and port that we're listening to so we can say host hoist one and the port will be let's just say 88 77 goodness there you happy now okay hmm not much of a change we just created lager we created an options object and all we did really here is change this from create to create micro-service and then here instead of passing a port number and listen we're actually passing a callback so if I go to my terminal and say yarn start death okay hey everybody I had to restart it I don't know why it didn't show in the first round maybe I forgot to save so here we can see microservice is listening microservices listening so at this point our server is set up that's all it took guys all we had to do is make a one little minor change in a decorator for the in the controller and coming to the main TS and instead of doing this factory create we do an S effect to recreate microservice and we have this little options object because we're passing a a bit more information just a port number as we often do within HTTP service okay so we have our micro service listening now we need a client that connects to it so now we're going to swap over start from the beginning again with that app but we're gonna rip out the micro service and inject a client instead that's gonna connect to this micro service and use it instead of that internal code so now that we have duplicated this into a proper project and then modified it to be a micro service we're gonna do the same thing again I'm going to duplicate this and then we're this time we're going to modify it to be a client so here we are back at the starting point but this time instead of modifying it to be a micro service we're going to leave it in a standard HTTP service configuration remove that math service from the source code and configure a micro services client that we can inject in place of that math service it sounds a bit more confusing than it actually is hopefully to keep things clear before we get into the whole providing and injecting we're gonna focus exclusively on configuring the client to do that I'll comment out this bootstrap code I'll try to there we go and we're gonna input some code here too to configure that client and have it contact our micro service let's start with some import statements so I'm going to import from ness Gia's microservices if you haven't added it for this project yet make sure you drop to the terminal and do yarn add in SGS microservices from here we want to import the client proxy factory and transport yep I also want to import logger I'm this just come good let's create a logger the mess micro-services option object is going to be the exact same object that we use for the server so I can actually just paste this in alright and then we're gonna say constant client and here's where the magic comes in equals client proxy factory got sinned actually I'm getting out of myself create microservices options and it's giving me an error because well it is the correct uh-huh well perhaps if I just do this client options yeah okay so that fixes that now let's make the magic happen client dot sinned and then we're gonna pass in for this it'll be number and number array add and then what some numbers to add about one two and three and then we're going to subscribe to this subscribe I'm gonna say whatever the result is I want you to log that result add some spaces so the Lynch it will be happy looks like we're pretty good so if you're wondering what some of this is I'm just maybe it helps if I just kind of put in a comment here return type RAM type pattern and per am right so when we do the client and we call the syn method the first in this type is that we're gonna put in is going to be the return type and then the second one is the params as you can see here we're passing an array of numbers therefore this should be an array of numbers we're expecting back a single number just a scalar value so this is not gonna be an array it's just going to be the number we subscribe to the result just like you would do with any observable so when we boot this up we should see the sums of these logs to the console let's let's give that a shot I wonder if I actually left the other one running I guess we'll find out soon enough ah makes for a few so I'm gonna say that I probably forgot to actually boot that other server on so let me go do that now so now that I've kind of blurred out let's try again and we get six right there lot so I can actually change this and since node mines gonna restart it when detects changes if I were to add five to that let's save again we should get eleven I see so everything's working with the client now at this point all we have to do is we don't want to use this in main right we want to use this in our controllers so we're going to make it so that this can be provided and injected in the controller that's the next step if we wanted to and if we were following the nest documentation we could go through the trouble to make a provided service specifically for this client proxy so that we can inject it into our controller however we're already injecting this math service that we were going to delete and I think it makes more sense that we use that service layer for what it's meant for and that is to provide an interface to our controllers but you know leave the implementation elsewhere so we can leave this in place instead of deleting this math service what we're going to do is we're just gonna change the implementation the function signature will remain the same but instead of actually doing this calculation ourself we're going to instantiate a client and use that to reach out that way new controller changes are required at all to to move my gratis implementation of the math service so let's first clean up our main TS file so we're going to kind of return it to what it looked like before let's take all of this and actually I'm just gonna take this out and we're gonna paste it into the other file because there'll be some pasting being performed here okay so first off let's take this line put it up here we'll be needing these things actually we won't be meeting all of them I think here we'll need a client proxy instead yeah then I can make a variable and then let's have a constructor so we can instantiate that client client proxy factory create kind of retyping some things I don't need to down here perhaps I should just do this okay and then instead of doing this what we're actually going to return is this little feel we did right here turn this client we're going to change that and yeah I think that's all we need to do guys let's remove this make a new line in the file I really hate when it formats it like that I don't know why yeah so we're just this math service is already injectable all we did was change the implementation of this accumulate method to use the client proxy and we don't worry about injecting this or providing it anywhere because you know it's gonna be included under the hood with the math service that's already configured so at this point I think we're ready to give this a test drive so I've got this laid out side by side on the left side is the Micra service that we've created on the right side this is the HTTP app we created that uses that microservice and down here I have my insomnia window which is like postman which I've been used to make a post request to the HTTP server which will contact the micro service to fulfill that request and then return it back so let's see if everything's working as expected first I'll do my start my server up for the micro Service it's listening so now let's do the same here start at the HTTP server looks like we're ready to go there as well so moment of truth let's just add numbers together five four and another four let's try that click send sure enough we get 13 back we can see that it hit here on our HTTP server and we can also see the HTTP server to fulfill that request reached out to the micro service so we've got something working guys I mean we've accomplished something at this point if you've been following along that's great you know actually like you know coding if you haven't been coding along you want to kind of just jump to the code look in the comment section I will have links to the repositories with tags on start and finish for all of these files that's about it for this video let's review where we're at in a series next we have just finished the video on micro services using TCP so that means that Redis is up next we're gonna use a message broker I think the next video is gonna be a lot shorter we had a lot to cover in this initial video using TCP most of that's not gonna change when we switch that underlying transport from TCP to Redis so look for a shorter video next and then T RPC yeah that's probably going to be another longer one see you in the next video
Info
Channel: Brian Johnson
Views: 26,733
Rating: 4.9162641 out of 5
Keywords: nestjs, microservices, nestjs microservices, tutorial, nestjs microservices tutorial
Id: IpoaVi9iPWI
Channel Id: undefined
Length: 24min 10sec (1450 seconds)
Published: Sun Aug 11 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.