Creating a Multi Service Spring WebSocket with Active MQ Message Broker

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys how are you today i'm going to guide you how to create a microserve application using websocket we'll create a backend application using springboot we've supported the website after do that we also create two front one front other one front end application that will be able to connect to our back end through websocket protocol so we have the client a client b both are connected to our back end here back end here and we'll be able to send a message from client a that will go through our back end and the back end you push that information to the client b this is the nice about websock also that we have the communication established between a client and the server the server is able to push information to that client right so clients just keeping listening for data chem through websocket it's different that if a client needed to implement some kind of rest calls where they call a endpoint in your back end wait for the response and to keep running in this case not we have two connections established between the client and your back end and the back end can push information directly to our clients after we implemented this part of the the the tutorial we'll make one very important improvement here that just in case you have to implement the solution production usually will deploy your backhand in a cloud environment using docker use the kubernetes in the aws i don't know no matter but it's important that to notes is that this instance of your backend service here it we can have multiple instances running at the same time when in production so if we have if we have more than one instance running a second instance here let me draw second line here we have the instance one and instance two running together in the cloud environment this leads us to a problem in the basic scenario the problem is the website connection is made directly to one service so even if you have a load balancer in front of the requests no matter a proxy the connection established always with one service so we can have have a situation where the client be made a connection straight to the services too in this case if the client a tried to send a message to the client b our back-end service using a basic implementation could not reach the client b just because it even don't know that the client b exists because the connection is made with other instances of the service how we can handle that situation of multiple services running at the same time in the clouds and even with that situation allow both clients to communication we need to integrate this solution our back-end solution with a new piece of technology that is a message broker we can add a message broker in the solution and as a message broker we can use activemq for example and we can integrate your backend to connect in that broker and delegate the manager of the session to the message broker so for our application for our backend application it's transparent you do not need to create so much code to handle with that situation but also that we have this messenger broker in our architecture what you'll be able to do is when our backend one try to send a message to the user b they wish because the message will be sent to a message broker and the master broker under the rules will do the magic and to the service to push the messenger to the client to be okay so this is what we will do in the code today okay let's jump to the code now we'll create a small web service application using spring and with basically rest endpoint and after that we will add some websock support to make some tasks so once that we have the spring initializer open let's create a default application here our default package will call of example dot websocket we can call this application of just websocket this will be a demo for websocket and i will remove this double websocket name here in the package now there is some definitions that we need to add to here as a default let's add the web support websocket we also add the security oh i choose wrong here secure it and also lombok to help his lock and that's some steps there once we have that let's generate the package will be download here i will just uncompress this package inside my project i will open my project folder here just drag and drop the project it's here and now uh i will open the intellij inside this new project let me show here the correct one it's websocked and we'll be open the maven project inside the this new project it is open here in the new monitor okay so here we are with a very basic structure for our project we have the default attribute here default dependence here and what we need to do here in additional is rename the application that prepares to imo file i think it's better to do the configuration in the email file i added some server parts because i want to run the application in the 8181 part and not the default one what do you do now it's create a rest controller just to test our application and during this tutorial i will copy and paste some code inside here just to do not take so much time to show you how it's work and all the code that we use will be available in my git road you can find the description here in this video in the description or what else so we are creating the red message controller this will be um a rest controller i'll add here the log4j supporter for for logging it will be up let's create the method first send message and we also add here to user we won't be using now but will be useful in the future i'll just copy and paste the the log information here and this will be the body of the post so let me have quest body and here you'll be the path variable and this method will be a post post mapping and we can use here the path that will be v1 to user okay i think it's enough for this first rash controller it's something that you can start the application and try to see what will happen let's open here and see what happens okay it's supposed to start everything's okay okay application starting running what we can do now is i have a postman here open with a collection empty it's websocked we will create a post request send message will be a post in the local rows 8181 we can add a body that will be hello and we are also at the vr v1 the one two user id let's use the websocket a1 81 it could be ever everything that we want i just standardized here okay it's not at our authorized because we added a dependence here that is web security so if if you also try to open a web browser i will open one in cognate here i think it's uh it's here and localhost localhost 8181 we you see a login page what do you do now we don't need this level of authentication here uh let's just add one configuration inside your project to disable this this type of authentication to disable that we can create a web security config here i will copy and paste some information first will be the necessary notation will be a configuration with enable web security and we'll overwrite the configure method because we will need to extend the web security configure adapter so here basically we add a configuration to allow every um request in whatever is the path that we choose so let's restart here our application and see what's happened let's just be starting while it's starting we are open here it started and let's send let's see what's happened okay we have 200 add response it's okay if you take a look in the log file we can see rest send message hello to user double x 8181 that would be the log that you put here this just means that our application is running and up and we can file a rest request inside that until now you don't have anything about websocks just the dampenings inside the the pawn applique the pawn so now it's the time that we can start to add the absork support let's close all this information here the first thing that we need to do is add a configuration to configure the websocket inside our application we will do that just creating a websocket config here and i'll copy and paste some more code inside this class basically i will copy and paste the annotation that will be necessary be a configuration we will need enable the websock message broker and also a log4j here and this web this class will extend another one that you will need to implement some methods and now is that came the configuration first we will over ha we override the resist stomp endpoint here is the end point that our client application will connect to our back end through websock we will enable the with sock js just to allow the library.js from the client side make connection for with our website or with our microservices and another override method that we use will be the configure message broker this is where message will be put in a topic and a prefix for our connection in addition to that i would like to introduce more one piece of code that i think it's important that is when the client try to make the first connection through websock i want to intercept this connection and perform some kind of validation it's where we can for example check if the user is correct or made some kind of authentication so we'll create an interceptor and resi register this intercept inside this websocket and it would be possible to intercept this first connection so let's create a class here it will be called called websocket interceptor genuine interceptor i again copy and paste some code here here will be a service with log support it will implement also a new class channel intercept and now more than that i will copy a big piece of code here but it's not so much different it's not a big deal it just should take time what this code is done is doing basically i override the present method that is before the connection between the client and server be established this class will intercept this connection and we can read some headers body and do whatever we want to do if you have a system to authentication we can just check if your user and password for example is valid you can do anything anything that you want with this interceptor so here i'm just reading the headers that came from my client and let me create a user that will be returned for the client that request made this request and also i'm logging some information and to to register this information inside your configuration we will need to override other method here basically we will uh we will need to autoride this websocket channel interceptor and we also needed to override an intersect inbound channel method here so basically we are made a registration of this intercept inside the configuration okay the this step is done i've made the necessary configuration to run now what we'll do is test if the connections are being doing correctly with your back back-end however to do that we needed to create a small front-end application it's just a piece of code with html and javascript where we can put some information clicking connect and establish a connect with our backend that's what we'll do now you can see here that you have a stacked static folder i will copy and paste some files inside and show you the javascript and what they do i'll copy here some files basically we have a cscs file just to handle correctly the html html with some fields not nothing so much here just fields to type information but what is most important here is is the javascript file because inside this javascript you have some functions that will be used to establish the connection with the backend and what is important here is the connection function basically we get some information from the farm inside the html and we create a soft js object point to the ws register endpoint that is configured inside your back end here let me show you website config we have the register endpoint here um in addition to that we also have the connection function that is called from the stump object where you are passing two headers one alf key and one id the off key we are doing nothing with that information inside your back end but it's just to show you how you can pass information through headers that could be uh one one type of key to make authorization in your back end your any kind of proxies that you have in front api gateway or whatever and after that we have a subscribe into the topic that we defined also here in the config we have a topic here a configuration okay so we have the connection function that established the connection passing some information for the back end we also have a send message a send private private message here that we will use later okay also that we have that configured here let's start our application again and let's see if it's if the connection is working correctly so we'll close this web browser here okay it started let's open up incognito window also that we have the the application up and running if we type local road localhost 8181 it's supposed to show the page let me just open this web browser again because i think i forgot one more things to do i will open a new incognito window here and to make this this applic just html fully work in you can see here that in the header we have some js files being referenced and to this file works we'll need to add some dependence inside the pawn and basically it's dependence to web jar i'll copy and paste the dependence here in my palm file basically our dependence for boo for bootstrap web jar we have the jquery support the stomps apart and so on this will be important for the web page works i just have to refresh the palm here and just restart the application again and the application will run and we can open uh incognito browser again just to refresh let's see if the application is running it's okay it's running again local rows 8181 we can see here the html basically we have the off key as i said we are using this information for anything inside our web backend application but we can use to do some some kind of authentication the websocket id is a unique id that you can provide for the back end for the backend identify the websocket connection this is something that you can generate in the back end but just for the sake of the example i'm sending this information to the web the front end so i will choose ws8181 could be anything that we want and file connection okay here we go so we have a connected status this means that the connection worked so we have a website connected between our client and our backend if we take a look here in the console console we can see one piece of log information that is user width of key abc id 8181 section blah blah blah connect and generate the user password object that you will choose so this information is in our interceptor it is here let me show you in the bug mode debug mode mode i will just close the application you see that automatically the front-end detect that there is no more connection between the client and the server i will open in debug mode at the breakpoint here and just make a connection again and you can see now that between this connection be returned to the client we have it intercepted for our back end it using the connect connect status so we can read some headers that will pass through this connection here we could perform some type of authorization but i'm just creating one object user password authentication token and logging the information and return it back to the client so we have here again a connected state so we just could validate that the connection is working now is the time that you we can implement the communication between these users now that we have the connection working it's time to create a controller just to allow one front-end send message to our back-end through this new controller not calling a resting point but send information through this website connection so i will just shut down here application close all this information and i will create a new class here it will be called websocket controller web web soft controller i would just copy and paste more some code here basically i will copy and paste some annotations with log4j 2. this hashcontroller will be a method of posting that you'll copy and paste here i will show you what it is done just comment this for a while okay what we have here basically we have a website controller it's a little bit different from the the controller that we call through rest and points because it's not a rest call but this information will come through a websocket connection so we have the method a principle is one information that's being injected automatically to you inside the the signature of this this method it basically has the information of the the user that was logged in the front-end so you can see here information like the username or the user id for example it's the more more important so we are we are we are receiving here off key that we also again we could use to do some kind of obtain our authorization or authentication in a proxy we have a two user in the path variable and a message as a body so on also that we have that we would won't test that yet because we needed to add a service a websocket service the webstock service will be the piece of code responsible to send the information through web software to other users that are connected basically they use the spring websocket framework to do that so we will need to create a websocked service here again i just copy and paste some piece of code starting with some annotation the header and basically the body will be like that i will just explain to you what it's doing we have here a simple message template that is one class from the spring framework the websock support is that class that will handle the information that we need and send information to other clients we have some method here a notify user and send basically what i'm doing here is just receiving the user id that would be the identification that user provided during his first connect to our backend and the message the important line here is the is the 20 20 22 line where you say convert this convert and send to user send to user user id the information that you put in this variable here that is will be at json and add this information in a topic this will be the most important line in the code because it's that line that will be responsible to send information back and forth to different connected users what you can do now basically is inject this class here in our websocks controller and uncomment this line of code okay so we have done our website controller is the class responsible to receive information from our clients through websocket and redirect this information to other clients connected that should be identified by the two user value here what we can do now is start application again we'll i like to open a new incognit web browser while always just to make sure that the code that is being loaded from the browser is fresh and not came from any cache okay we have the application running here let's let's fill some information here the off key we can't choose anything abc the websocket id is important here it will be the identifier for this clients that are being connected to the backhanded so you choose double s 8181 will establish the connection we can see here that as a returning as a username returning we return it the same websock id that we provide this is done in the interceptor it's good to know that here in the intercept when we had turn a user to the front end we are putting as a username the same websock id that the customer that the client send as websock id it could be anything but i'm just reusing the information and now came the important part i will send a message to the user id 8181 and the message will be hello from 81.81 sent okay take a look here what happens basically this information was sent to the backend through websocket the backend just push that information to the same client and it was showed here if we go to our controller and put a break a breakpoint here i have to start again in the debug mode we lost the connection while you need to connection gate 2 just to make sure it's up and running okay it starts i'll make the connection again with the same information it's connected i just send the hello again and now our websocket controller was breaked so this means that that that information arrived in our back-end we will send that for it will pass this information for our services that you call the send user and put the message in the message broker but the message broker here is just in memory we are not using any external message broker okay so i will just play here and here we have the same information again what i can show to you now is how to make two application communication so we basically we will open another browser here and we will establish a new connection one two three this we will be the web ws 81 81 b will connect we are connect with a new id so i will send one message to myself here just to make sure it's working hello from 8181b oh it's i i i had the one breakpoint here just to follow okay okay we have a message here it's very teeny but it's arrived no what i i'm i would do now here is inside the the client b that i have connect i want to send the message to the client a so i'll just copy and paste the id from this client i'll put this id here as a destination and send the hello from b from here okay we have here the message arrived that match come from one client to other so here i would do the same i will send the message a message to b and hi if i go to the client b i have the information here so it's worked basically we have two separate separate clients connected in our back hand and we can make information and we can make we can send information from one to other true websocks what i can show to you now is one problem that for this test we have just one instance of the back end running so these two kinds are connected to the same back-end to the same application running and if we have two application running with different clients connected to them they won't be possible to communicate to each other because they are running and managing website section in memory so we need to add an external broker in this architecture i would just to you show to you that won't work so basically what i will do now is duplicate this running here we'll call this one off 8282 and after doing that we are add some vm option here and we will add some d i'll copy and paste this information it would be better basically we will change the part of the application to 8282 i'm just setting the server pawn dot part here and this will have place this information here for 82.82 so i will open the first application that will be running in the 8181 and i also will open a second instance of this application inside the 8282 just give a play here too and we now have the two applications running so what i will do now first is close my income into browsers again and i will open again so now what i'll do i'll connect one client to 8181 and another one to 8282 so we have two services running in the back end and each one of these clients are connected through websocket to one of the servers so [Music] as off key abc for the first client i will call ws8181 i will connect it is connect here i will do the same for the other client abc as a websock id will call off this client as ad282 it's connected i'll send the message to myself here 28282 hi from 8282 you can see that it came it's arrived here uh if i send a message to myself to 8181 hello from 81 year one it's also arrived here however if from 81.81 i try to send the message to 8282 take a look here we have no errors of course but the message does not arrive in the second client that's the problem because we have a separate instance of the back end customer connecting in one of them both however the the websocket section are not men are not managed centrally this is the problem that we have here so if you have the situation that the back end needed to push information to the clients we can deal we can uh we can lead to a situation where the client does not receive that information that that the reason that we need to add one extra message blocker here okay what will you do now is run a local version of active mcq as a message broker we use docker and docker compose to do that and connect our application to this this message broker so first we will go to our application we will create a new file here that will be broker compose yemo i'll copy and paste some information that is the composer the composer to use the image of active qr themes you are setting up the username and password and exposing some parts inside once that we have that we can go to our console and go to the project folder and run docker compose f broker yemo up and q this will run the artemis message broker in our machine also that is up and running to see if it's working you can access the 81 61 part it needs to show the active mq page if you go to the management console and type your chemist our canvas you can see the the application running here just you'll see that it is up and running so we have now one message broker running what you need to do is integrate your application to this message broker how you do that basically it's not a big deal you have to use the website configure again i i will open the application too again i will also copy and paste some code here just to make things more fast basically what you do is put in your emo application some information regarding to where this message broker are basically that the messenger broker is running the local rows the username and password these are tems and the parts that are exposed so also that we have that we can go to our configuration and i'll just read that information from the config file here so basically i'm putting inside attributes from this class the values that use in our application and the main difference will be here in this method it is where we need to configure the connection with the message broker so i will comment in this line and but this one here is the same hazard hazard that i'm using here let me just show you what we do here is other than use enable simple broker i now i now use enable stone broker relay and in additional to just use this new method and pass more information to this map to this object that is the host the part the user the password all the information and some additional uh some additional topics that will be used if if the client won't be detected the messenger broker handled this information to other topic to deliver to the correct user so also that i have that it's supposed to work so let's open the application again the integration was done let's see if it's nothing bad happens here okay we have a problem okay we need one more dependings inside your palm class so let's fix that what we need to do here is to add more two more dependents in our phone we need to put here in our phone the net hector and the net hector car i have the deafness here let's just copy and paste inside our phone net reactor reactor net and your current car so let's build and open the application again these two themes are required to run the application connecting to the message broker so the application is starting now okay it started so we can close that one and what we'll do now is open the same two applications i started the 8181 service and now i started the 8282 and will you keeping open two micro services one in each part however the both micro servers are connected to the same message broker we will perform the same test that we did before however now with the active mcq in place okay both applications are up and running what you do now is just reload the connection to the 8181 and way to 282 let's perform the connection again the app websock id of this site will be 8181 i will connect it is connect take a look here now in the connection response we can see that the response say that we are connect with activa mcq are thames so we will do the same for the other microservice 8282 connecting now came the fun part if we send a message to ourselves hello from 8181 okay we receive here i'll do the same in the other side send the message as user destination with the 282 hello from 8282 send the message here and like what what i can do now is from the clients that are connected to the second second web service and microservices we can send as 8181 destination not here but it's here i've sent and you can see in the other servers that we received the the message and here i can do the same from the 8181 client i can send as a destination within 282 and we can see here that the other application received the message this shows that putting one active mcq message broker in this solution make that even if we have two instances of the microsoft running with a website connection in each one they could communication to each other passing the message through this microsoft this is very good because we if you have some if you have a solution in the cloud and your application just scale out with many multiple multiple services running this certainly happens one thing that we can do now that we have the active mq in place is just make a little change in that controller rest controller that we did and if we can just try just make a request in this controller and send this one message through websock to one of the clients what we can do here is just inject the service the websocket serves and also that we have the service here we can call the notify user passing through the parameter the to user and the message here so we have a resting point in this case that will send a notification through websock for one of the clients that are connected and then that isn't in fire by this 2u 2 user here as i made a as a major a change here i needed to close one of the servers and just starting again and while it's starting we can take a look in our postman here okay i have the the request in place the service just start right now 81 million one it's here i can connect again okay it's here let's see if it's working now uh i i fire requests to the service 8181 and try to send a message to the user 8282 however this time will be a hero from the rest endpoint so here we have the 8282 client it is connected let's see what's happened okay we have we have successful the key successful here and now we can see that the message just arrived in the client this means that even a request that came to our services through a rest and point we delivered the message through websocked we just push that message to the client that is identified with this id one last thing that i would like to show you how to do in this example is to how to detect when a client connects in your service and also disconnect because we have an interceptor that is that can intercept the connecting request from a client and do in perform some kind of authorization or authentication but after the connection be established we also can detect that disconnect with successful and we also can detect when it disconnect this sometime can be useful if you want to manage it when a client is connected and disconnected and if we record some information the database manages how many clients are connecting our backends and so on so let's do that now what we needed to do now it's stopped our service and create a handler to handle the connect and to handle the disconnect so let's create a two class here we'll call web socket connect handler let's just name here connected connect angular and also other class that web sucked disconnect camera web suck just connect handler again just give us a fixed typo here okay in the connect handler we have here the connect handler i'll copy and paste some codes inside here in this class we have i look up the whole class here to show basically this this class you implement an application listener and every time that a customer was connect with sus4 in our backend this class will be fired and we can detect on application event that the user are connecting and what we will do here is just log some information user the name of the user that will be the id that we are using connect to the section id this is the section that was created automatically when the client is connected with your backend so this class is responsible to detect when clients are connecting the same that will do with the disconnection one i'll also copy and paste the code here it will perform the same way every time that the client disconnect and the disconnect can happen for many ways if you lose the internet connection or the network is broken will automatically be disconnected from the back end is something that could happen and if this happened the client needed to connect again he the client needed to keep control of if he is connected or not so we can detect that on the backhand side and perform some action like remove this this user from the database or from some some table if you are just records when a client are connecting and disconnecting you perform some kind of control in addition to that we also need to create a configuration so you just create more one class here that will be the websocket handler config and again copy and paste the information here basically just import this section will be from the spring okay basically what we're doing here is just register these two handlers are connecting this connection for our websocks now i will just open the 811 application again i will just let me open here in the book mode just be better to show okay it's starting okay just to start let's just clean the log file here and oh okay here we have the web web front-end application i will just reload and now i will make a connection abc 123 connect let's take a look in the log okay almost that i did perform a connect we have two important logs here the first one user with with off key abc blah blah blah was the log from the channel interceptor this was what received before the connection happens that's where we could perform some some authorization but the second one the websock connection handler is the log that was performed after the connection be established so here we are sure that the client made the connection with our backend so we could perform some actions like record that in the database that this user just are are connect okay so in the same way what you do now is just close the browser let's see what's happened in your back end take a look here websock disconnect and handler was trigger and user one two three disconnect from blah blah blah so this happened that this show was that when the the connection was broken with the backhand your backhand could detect that and again we can perform action based on this so guys i think that we did here a good example of how to use websocket with spring application and also use one active mq broker to manage the sections and we can handle that situation where we have more than one server running and even if you have scaling or backing server we can keep keeping communication between these clients all this code is available in on my github you can use as you can if you have them in doubts or in comments feel free to to contact me so guys thanks so much for watching this video and see you next time bye
Info
Channel: Edu Costa Dev
Views: 7,026
Rating: undefined out of 5
Keywords: spring, websocket, java, microservice
Id: pj0zVBOUd58
Channel Id: undefined
Length: 61min 57sec (3717 seconds)
Published: Sat Oct 16 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.