Intro to Azure Service Bus - The Power Behind Microservices

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
message buses and queues are a powerful tool for communicating between applications they are used extensively in microservices but they can be useful in larger applications as well in this video we're going to look at how to implement azure service bus queues into our applications to both send and receive messages the best part is that even though we'll be using azure it's only going to cost about 5 cents per month to use these cues even in production now if this is your first video you've watched of mine my name is tim corey and it's my goal to make learning c-sharp easier i provide videos twice a week here on youtube to help you grow as a developer i also have a full set of training courses on iamtimcory.com i would encourage you to check out all the resources i have to offer in this video as with most of my videos i'm going to create some source code if you'd like a copy of my source code use the link in the description to get it let's get started with azure service bus so we're going to create a new project i'm going to start with a blazer server project let's come down here to blazer app this is going to be the the thing that kicks off the queue that creates the queue message we're going to talk about what cues are and how they work in just a minute but the basic structure of our application is we'll have a blazer server app where we have a web form you fill in the web form with some information you hit submit that's going to send a message to the queue we're going to have a different application we'll use a console app for the other application we have a different application that listens for cue messages and then it will do something with those hue messages which is just display on the screen that's all we're going to do but that allows you to see both sides of the process i will create a shared library we'll do a net standard 2.0 library for that we have a shared library that allows us to create a model in the shared library we can use in both the blazer app as well as the console app so we have that basic structure for our our system i really wanted to do two different projects for this because of the fact that i want you to see how to have a sender without a receiver in the same project in a receiver without a sender in that same project so you can have those disconnected because there may be a case where your application isn't doing send and receive it's just doing one or the other so i want to show you both separately so you know what each piece is and where it comes from so blazer apps the first one let's give this a name of sb sender for service bus sender normally i don't abbreviate but in this case i didn't want to call it service bus sender because i didn't want to confuse you with the official service bus stuff so let's call it sb sender the solution name will give a different solution name let's call this service bus demo that's just for you um just so you you can see a different you know that it this is the service bus then when you're looking at your folders but it won't change any of our namespaces okay so sb sender we're going to do a blazer server app no authentication just https no docker hit create and then once this gets created where i right click on a solution we'll say add new project let's create a classlibrary.net standard and we'll call this sb share shared and hit create and we create class library the first thing you should do is delete class one note that since you did that you cannot add this sb shared yet as a reference in the sender project because there is nothing in that namespace now but don't worry about that we'll get there in a minute add one more project this is going to be a consoleapp.net core console app and we'll call this sb receiver and there's our console application so those are our three pieces we're gonna have our sender we'll have our shared and we'll have our receiver so sender's gonna send the messages out now in the sender we're gonna right click on dependencies manage new get packages and we'll go to browse we're going to look for microsoft dot azure dot service bus this is from microsoft so microsoft.azure.servicebus this is what you're looking for hit install and accept i believe there's also a windows.azure.servicebus don't use that one use the microsoft dot azure dot service bus all right so there's the one nougat package we need now also come down to the the shared project right click and let's add a folder here let's call it models and inside the models folder we're going to right click and say add new class and let's call this the person model make it public first name last name and let's leave it like that just just those two values i am going to do this though and say required which control dot well once we ctrl dot to install the nuget package system.componentmodel.annotations and that allows and also puts a using statement up here but that allows us to say that these these two values are required in our form just a little bit more um niceties really it's not necessary but for a demo purpose at least but this way you can kind of see you know how you do it in the real world okay so that's that's basic one more setup thing right click on dependencies in sb sender and say add project reference to the shared project not the other way around you can only have a reference go one direction so the shared project will have no references to the other two projects now since i did both of those in the sender if i click on the sender project i can just copy these six lines so both the reference to the shared project as well as the package reference to service bus i can copy those i can click on receiver and in here and paste them in and now the receiver also has a package reference to azure service bus and it also has a project reference to our shared project so it makes life a little easier and that's all we have to do with sb shares we can kind of minimize that and now we've got the the initial setup work done so let's talk through um what is service bus and why are we using it instead of just communicating directly or going through a database or something like that so first i do want to point out i used a a net standard 2.0 class library here you can use a.net core library that's cool if you use a dotnet standard 2.1 or beyond then it will not work with net framework projects that probably isn't a problem for you unless you are trying to keep some backward compatibility and i i try and keep backward compatibility if i can um just to demonstrate how you would do it but um if you're doing fresh new code then net core is fine um especially going forward so um that's what that is okay so i have this website here and i could tightly couple it to my receiver so i put that code right in my sender project but let's come up with a you know a simple scenario where this might be better not to do that so let's pretend that our sender is a website that captures information about users so you come in here you log in you create account and it's going to email you and say hey thanks for joining the you know the family and here's some cool information about what we do well i could put that email or code in the same site that captures all of your information but then what if i have to take down the email service or change the email service i have to take the whole site down including the rest of the the website that's not ideal so micro services the idea is we break out a piece of our application and make it an entire application that does one thing and so we can say well our microservice would be that email system where all it does is send email that's all it does it doesn't know who or or when you give us all the information in the input well that would be what our sb receiver project would look like it'd be a little service that sit out there a little um system that runs that all it's going to do is listen for new emails that need to be sent well how we how do we know when a new email needs to be sent well when a person signs up in this sender website there are filler information in and then we're going to send them an email so we'd have to some way tell this micro service that set this receiver hey go ahead and send an email but how do we do that without being directly connected to it i could add this as a reference and then trigger some kind of method but that seems cludgy and again if i have to update the sb receiver now i have to hit the website down still because it's tied together and so we create this idea comes out that has been created called message buses or in queues and the idea is it's kind of like email it's not nearly as inefficient but it's kind of like email and so what's going to happen is the sender is going to send a message and it's going to go to a mailbox called a queue and that message is going to pop in the mailbox and that message says here is the person i need you to send information to now in our case we're just going to send first and last name that's all not even an email address and then the receiver its job is to look at that message queue that email inbox and wait for new messages to come in now you know in the old days you might have pulled the database and said is there new things to do is a new thing to do but that's inefficient and so with a message bus you can listen for changes and that's what's going to happen the receiver is going to listen to the mailbox and say when something comes in i'm going to do work and so in our case we're going to do is just basically print out the console hey we got a message about tim cory or about sue storm or whoever that's all it's going to do but that would be where we do the actual emailing or we'd say send the email out and actually you know do the work of sending the email that'd be in the receiver and the cool thing is you don't have to have just one of these cues you could have lots of them and you probably will where you'll have a queue for you know sending an email maybe you have another queue after the email gets sent where you say i sent the message now put a new message in the in another queue that says i just sent a message to bob smith and that's going to trigger the next action which is something totally different maybe update the record in the database saying that they got the welcome email or something like that so you can have multiple of these this is what micro services use to be totally disconnected because the cool thing is i don't have to have the receiver running if i send messages to the queue they go to the queue if the mess that the receiver is not running the queue just keeps getting bigger and bigger and bigger that's fine because when we turn the receiver on it's going to process all those messages so we can take this down in the middle a day and it won't affect production it'll pause certain actions but usually that's fine because saying email out is not time critical it's not like if you sign up you have to get an email within seconds unless it's an email like confirm your account or here's your password or something like that but if it's hey welcome to the family this is what we're all about that's not you know second critical that's not minute critical you can send it out hours later and it would still be relevant and still leave fine so a lot of times you can take these services down work on them and update them in the middle of the day and not hurt anything because you have these cues and they're what allows you to kind of pause the operation while you go do work update the system bring it back online and then let resume and we're going to see that in today's demo okay enough talking let's start implementing so on sb sender we're going to start here and create and do some work so right click and say add folder and let's call this services and in here we're going to create a class and let's call this class the q service and in here i'm going to create constructor i know i need to have access to the i configuration which does add a using statement up at the top microsoft.extensions.configuration using statement and we'll call this config control dot to create and assign the field now i can access the app settings essentially and in here we're going to have one method public async task send message a sync and it's generic type t if you're not familiar with what generics are or how to use them i do have a whole video on generics i think it'd be really helpful and just you know we're going to use some more advanced topics in this video um with json serialization and generics and i think like other things like that i do have other videos that cover these topics so if something's a little confusing pause go find a video on that on my channel watch it and then come back i think it'll be helpful because this is a really important topic but it's not necessarily for absolute beginners you have to have a few things under your belt like intro to blazer and things like that so t service bus message and cue name those are the two things we're going to ask for so we'll do a try catch here and we'll say catch the exception which we're not going to do actually you know what i'm not going to do a try-catcher because i want this to crash if it doesn't work we could catch the exception but if we do we probably we should log it which means implementing an i logger which means you know more work so i'm not going to i'm not going to capture that i don't think i'm just going to let it run as is if it crashes then we know we have a problem and it will give us the error message so var q client equals new hue client that's going to add a using statement for microsoft azure service bus so new queue client config dot get connection string and the connection string we'll call azure service bus and we're going to pass in the cue name now making this pretty generic not just the the t generic let's unpin this uh but generic in the in the sa sense that you can use this with sending messages to pretty much anywhere it's not limited to you know just hard-coded uh one place so we're up load the connection string from azure service bus we don't have that yet we're going to get that in just a minute i'll put the placeholder for now so we don't forget which is connection string this is important to get that right how we're spilling it an azure service bus and we'll leave that empty for right now but we're gonna come back to that i'll leave it open so that's the location we're gonna pull the the connection string from and we have to give it a cue name and the reason why is because we're gonna connect to azure service bus but you can have lots of cues inside of your service bus and we'll have dedicated cues for each different task now that takes care of the cue name but we're also passing in this service bus message and what this is going to be is the actual data that we're going to send into the queue now in a lot of demos you'll probably see a string pass in here and just say hey this is my you know my message well yeah cool but i think for a real world application you're going to want to pass an object in here a model and that's where you have that that shared project so that we can pass in that person model and then on the other end take the person model out but in our case we're saying it's a generic it can be anything you want it to be so person model address model order model whatever you want to pass into a queue whatever cue name you give us we'll go ahead and do that so next we're going to say var message equals new up let's do wow that was the wrong key um let's do message body first equals json serializer which is going to bring in um system.txt.json don't bring in newtonsoft.json this is the newer version system.txt.json newtonsoft is the the original version we use with json serialization it's a third-party library um but then microsoft kind of created their own and made it a little more efficient and so they created system.txt.json newtonsoft is still operational or selecting updates to it but i would recommend going with system.txt.json from microsoft so there's that additional using statement that it added right there so uh serialize we're gonna serialize our service bus message so the message you pass in whatever object it is we're gonna serialize it serialization what it does is it turns your object into a json object if you're not familiar a json object is javascript object notation and this is json so this is an object since this curly brace is right here and inside there is a property and that has an object inside of it let's make this one this is a property this is an object property so that the value is an object and then inside this object is another property and this is the value which is a string value so this is the the way that we communicate across the web for things like rest apis and in this case for um saving or sending messages through azure service bus so what'll happen is json is just a string that's all it is it's going to compress it down it's going to take a lot of white space out but that's what a serializer does is it takes our object and turns it into a string now we can take the same that string and then deserialize it back to an object kind of like you know dehydrating rehydrating our objects so we're turning us into a string and then we're going to say var message equals new message encoding which is system not text just to add that using statement at the top right encode it as utf-8 dot get bytes message body so this is going to convert this into a byte array which makes it really efficient to send across the wire and so we're going to convert it to that that's important to do and we're going to say await q client dot send async send the message so this this method right here is a wrapper around what really is this the send async but we're doing a lot of setup here we're creating the you know q client we're doing a connection we are serializing our data and then we are converting that to a byte array and send it create a message object out of that and then send that across to the service bus this is code i don't want to repeat over and over again therefore we get to call just this method and it does all that work for us every single time so that makes our lives a little easier now to wrap up this service key or this q service let's go up to the class i can click on the class name control dot and extract an interface iq service in the same uh folder and now it's got an interface so i got this iq service down here in startup.cs in our configure services i'm going to say services.add transient it's going to be an i q service it's going to add the using statement for sbsender.services and the implementation is q service like so they may ask well why you create the interface that's a one-to-one to this queue service and you know why are we doing it this way well the reason why is because now throughout my code i'm going to ask for an iq service an interface and i'm going to get this q service however if i want to do unit testing and i want to replace this iq service implementation with a mocked one instead i can do that because i don't have hard requirements i don't have uh hard dependencies i have dependencies on interfaces instead so you can watch my video on dependency injection or the the d in solid the depends the inversion principle and why that's important so those two videos will really help you work through that so that is now i've added this to my services so i can ask for this wherever i need to so i can close out of startup i can close out my q service i want to keep this open because i don't have yet my connection string for azure service bus let's go create that by creating our azure service bus here in my azure portal now if you're not familiar you can get azure for free you can use um you get the first i think it's first 30 days or first 60 days you get a hundred dollars in credit or something like that to try pretty much anything you want out but then you also have 12 months of free services and then you also have i think it's 25 plus things that are free forever so there's a lot of really cool stuff just a demo account so you can do a lot of stuff for free in your first year of testing you can do an awful lot even after that year of testing you get things like 10 free websites and a lot of other things they're free for life so really cool stuff check out azure sign up for it get a demo and um yeah just play around once you're ready i'd wait until you're ready because you want to take advantage of those hundred dollars and free credits and all the rest let's create a resource and we're going to search for service bus this is the service bus from microsoft notice it it's called azure service bus but since we're in azure it's just called service bus so just wanna make sure it's clear because you search for azure service bus i don't think it comes up it's a search for just service bus hit create resource group name we'll create a new one let's call this service bus demo and the reason i create a resource group here is because at the end of this i don't want to keep this around i don't need this demo service bus available so i will delete the resource group and then anything that i create in this demo besides the the service bus including the service bus as well will get deleted now we're just gonna have one thing but um the principle is there do this whenever you're doing demos create a resource group put everything that you do that one demo together in the same resource group and at the end delete the resource group and you clean everything up and you don't get charged for the things that you don't use anymore namespace name this has to be unique so let's use my fictitious company tim co service sir this bus there we go now i'm gonna delete this because i i will probably use the service a real service bus in the timco retail manager series at some point in the you know mid to near to mid future because we're gonna probably go into microservices and breaking things out and things like that so um this is getting get deleted though so it's not a problem let's put this in uh east u.s too you know what no let's put in central u.s i'm currently in central u.s keeps it close pricing options pricing tiers we only have three ignore the recommended because the recommended yes if you are a major company using this for major things then sure i guess that premium is the right way to go it's not for you um it's not for most people basic and standard are just fine we're gonna look at the differences in just a minute but basic let's go to full pricing details i want to show this off um because it's a big deal so basic you don't get as many things you just get cues we're not going to cover topics today but there's a cue and a topic a queue when a message comes in then a listener that's listening will pull that message out and it's one time it happens one time when you pull it out you remove it from the queue that message is no longer there so one thing handles it which is fine when you're doing most operations so if you're creating a new user and you want to send them an email you don't want that email going out five times so you pull that message out no one else can process it because you can have multiple things processing out of the same queue maybe you have five different servers running and it takes a while to process something they can be processing within five things there's one if you have five different servers running the queues so that's the the first in first out one time read kind of thing that's what a queue does a topic is that it allows you to have more of a a pub sub model a publisher and subscribers model where you can have as many subscribers as you want listening for messages so one message comes out and then may multiple things hear and process the message so that's a one-to-many versus a q is a one-to-one relationship now the basic which or what we're going to use is 5 cents that's 5 pennies us dollars per million per month so if you send up to 1 million q messages a month you'll be charged 5 cents that's it that there's no hidden cost there's no well yes but no five cents so that's why i said this is gonna be so cheap to use that's 60 cents a year it's also going to cost you to have a queue running that can serve your actual production needs now if you want to grow and you want to use topics as well and you want to have some better uptime maybe not uptime but better um throughput then you're going to get 10 a month so 120 a year for 12.5 million messages a month so even they're very very cheap for a lot of use now that dedicated the premium they recommended we have cues topics message operations stuff fixed pricing zone redundancy that's 668 dollars a month that's not what you need not not usually but this these two can serve a lot of businesses for really well so we're going to choose basic make sure you choose basic and hit create or review and create we're ready it's validated hit create and that's going to create our um our service bus for us all right that's done now i paused the video there i didn't want you he's sitting there through that so don't think it's going to take you know a second to create it takes more like a minute to create but we're done we can now go to i'm gonna go to the resource group this i think there's a glitch in azure i'm not positive but there's no marketplace message it's a little weird and go to resource will take you to the no marketplace version if you have a service bus demo the resource group and inside here you have timco service bus and it still says uh no marketplace but if we pin this to our dashboard the demos dashboard then go back to our dashboard we can go directly to it it doesn't say that no marketplace i'm not sure what that's all about it's a little weird um but whatever so in here now uh don't panic i am going to show you my secret password here it's okay i'm doing it intentionally i debated i can hide this thing but the reality is that i'm going to delete this anyways and i'll also show you how to basically kill that key and regenerate it anyway so shared access policies right here that's this little key icon you have the root mesh shared access key which can manage send and listen you can create new ones if you want that just for example send and create a policy name and create that um we're not going to create just where it's going to use the root manage one which is basically like an admin access so fine for demos but when you go into production maybe you want to limit that just to send or receive have different ones for each so right click on this and no it's going to do all three we have a primary key or secondary key our primary connection string in our secondary connection string which one you use doesn't matter you can use primary or secondary you can have different ones different you know systems use different ones so you have let's say you have an admin system maybe you make that the primary connection strings and then you have more user-focused ones you make those secondary connection strings that way if you ever say oh no we lost a connection string meaning the connection string has been visible to to end users and it's the secondary connection string onto this ellipsis you can say regenerate secondary keys and it's going to redo these keys and it's going to change these values so it's going to change this value here as well notice that this new secondary key is in this connection string so doing so allows you to do a quick reset and say hey we lost that we're gonna reset it which means you have to update your application connection strings wherever that was used but that's a safety and security feature to very quickly cut off access if a key is lost so i'll show you how to do that with the primary string in just once i complete this demo probably i've already shown you once i'm not sure if i'll show you again but i'm gonna copy this connection string i'm gonna come back to visual studio and azure service bus gonna paste that connection string there it is now if this were going to be and i'm going to i'll probably wipe this out before i give you the source code so when you download the source code you'll probably see an empty string here you have to put your own in sorry um anyways but if this were a you know quote unquote real application and this is my my uh development version of azure service boss i would right click on the project and i would say manage user secrets i'd create this entry in user secrets including the connection string and then remove it from the app settings.json so it doesn't go into source control i covered that in my intro to app settings video as well as my app settings in-depth course so that's our connection string but we have one more thing we want to do in here now that we have our connection string set up we're going to cues there are no cues so let's create a queue let's call this the um person queue for um for the person model let's just simple name max queue size how big do you want this q to get now these are messages they should not be massive if you've got megabytes worth of data coming through your q messages maybe think about why i believe the maximum size for a message is 256 kilobytes anyway let's go up to the premium plan um but you know so that would be a lot of messages that are piling up in the queue so think about your queue size but i think that one gigabyte is fine max delivery counts i had to look this up because i'm like why is why is that a thing what's that mean because you only it's once you get the message it's gone like it it removes it once you say yes i received that message well maximum delivery count is and this help does not help the maximum number of deliveries thank you captain obvious well what this is is when you say i'm reading this message then it puts a lock see this lock duration here it puts a lock in the message for in this case the default is 30 seconds well you have then 30 seconds to say okay i successfully read the message well if this lock duration times out it's going to unlock the message and keep it in the queue assuming something happened on the reader maybe the reader crashed during read or something like that the next reader will pick it up and say i'm reading this message put a lock on it if that happens ten times and it's not pulled out of the queue then at that point it's going to send it to the dead letter q saying hey for whatever reason this message is poison there's a problem with it something's wrong with it and we're not going to keep trying to read this thing it's now let's call it dead letter queue which is basically the we've got problems area and then you can manually look at that message and see why you're getting that um those problems so that's the delivery count message time to live the default is 14 days that's a long time for a message i don't think you need anywhere near that time but um it's fine i mean it's in all likelihood you'll never see a message live more than a minute or two unless maybe your application is down in which case your your um your queue will just kind of back up but if you haven't addressed your application being down for two weeks then those messages are gonna start to expire and if you want we can send the expired messages to dead letter meaning there's something wrong with them i i'm not sure if we want to do that or not i'm gonna say no to that and partitioning um this is a scaling thing you can learn more about but uh we're not gonna do partitioning either right keep it really simple let's do a simple queue hit create it's creating our cue done there's the person queue so we talked about earlier in our source code let's go back here and go to our queue service mary passed in our message and then the queue name well that cue name is going to be person cue because that's the the one cue we've created now obviously if you had other cues we could use those other cues as well but we're just going to use that one cue called person queue now we have the azure service bus set up we have our queue set up we have our connection string in let's go to pages and i'm just going to modify the index page we're not going to get real fancy here and create you know fancy pages we're just going to create a page or modify this index page that's already exists so let's add a couple of using statements first of all at using for and this is going to be our sb shared dots models and then another one for using our sb sender dot services and then we're going to inject our i q service and we'll call it q so we're just adding two using statements here one for our models which is our shared project down here and then one for our services which allows us to inject that iq service not iq but the iq service that we're gonna access in order to talk to our queue now again uh this is a demo project most likely i would not put the actual send to a queue right on the page instead i have this in a class library that you know gets called down into account got you know business logic and then data access this will be the data access layer to be in but we're kind of you know bringing it up to the rep to the top because there's an awful lot of setup we have to do for not much benefit this is where the difference between a tutorial and a real world application come into play this is a tutorial we're going to kind of crunch things down a bit i do try and point these things out but um a real world application like the timco retail manager or the c-sharp application from start to finish those kind of projects are where we do it kind of quote unquote right where we build a real application the real way not just shortcut for tutorial purposes all right let's get rid of the survey prompt don't need to see that and but right underneath here let's have an edit for actually let's create a code section first because we need to have a private person model called person equals new whoops equals new person model and we use this to create a form edit form and because of the way that um blazer server tries or actually just visual studio tries to do intellisense on this page i found it easiest to close the form out and then come back into it instead of trying to do it all at once model equals at person and then we'll have a valid submit in a minute in fact let's let's just mock it up for right now or create uh private async task publish message so that's what's going to be called on valid submit so on valid oops not at on valid submit we're gonna have our publish message so that'll only happen if it's a valid submit remember i put a little bit of validators on our model just saying it's required to have both a first and last name so in our edit form and again i've covered this in my blazer server in depth course as well i might have covered it in a youtube video on blazer server i'm not positive on forms specifically but we're going to have our data annotation validator i messed that up there we go and also our validation summary message and then we're gonna have and do a little bit of bootstrap here to make it a little bit neater div class equals form group and then we'll have a label for first name we'll say first name and then input text which is a blazer server specific tag called id equals first name and the class equals wow one too many s is there equals form control and we'll have a bind value equal to person dot first name so i've got here a label and input box that's being bound the infobox going bound to the first name property of this person object let's copy this we don't have to do that you know miss typing all over again and change everything to last name this is why copy and paste is not the best because you're gonna miss one of them if you're not careful trust me i've done it a thousand times ten thousand times probably and then you you wonder why uh control j brings that list up that way that's why you saw j pop up there last name um it's gonna happen if you copy and paste stuff you're gonna miss one of these last names in here somewhere and um that'd be a problem so i encourage you when you're doing it yourself don't copy and paste for video i do to try to make things quicker but in real life i don't copy and paste i will retype that all right and down here where i have a button a type equals submit button class equals btn btn primary submit so this is a little bootstrap form that uses the the blazer server syntax for instance tags this is an edit form it's going to create a form when it actually renders on the page but has some additional things like binding to the model and binding the submit to send to our our our method down here speaking of that method let's await q which that q is from our injected service q dot send message async where it's in our person and we're set to the person queue and then we're going to say person equals new person model so when you publish a message it's going to send that message to cue and then wipe out the person so we can start over with a new person nothing big and flashy here that's really all there is to sending a message to the queue now just that line right there this um the service this is generic you can copy and paste this put in your application and it will work for you and your queue and your service bus so it's really just this line right here that's different and the app settings.json that's different that's it let's run this we're going to run the sb sender only and once this launches we should see that form and we should be able to add items to our queue so tim cory submit it went away let's go over to our azure service bus and if we open up the person queue we'll see that we have one active message now you can come in here under the uh service bus explorer which is in preview you can do a peek and what a peak does is it's kind of what it sounds like it it looks at it but it's not actually quote-unquote reading it which means it's not going to take it out of the cube that's a non-destructive look let's do a peek and we successfully peaked and we have one item in here we click on it we see over here that the message is that json string of first name of tim and last name of corey so that's we can close that out that's our message so it went through properly let's go back over here and send a few more notice i've done c4 so sue sue storm and bob smith so i sent now three messages let's close this out and if we go back to here hit refresh we now have three messages we can peak and so we have all three in there we could receive these which would be destructive which is a receive and delete so that's why it says it's destructive and if you try and do this it's going to say do you want to perform a destructive receive no i don't i'll leave these in the queue as they are because we haven't figured out or haven't completed yet the second half of our our solution which is the receiver we haven't done anything with the receiver so let's deal with that now because then we'll have something in the queue for it to receive this is a cool thing we haven't written it yet we have messages already piling up in the queue it's okay once we complete the receiver we'll launch it and those queue messages will pop in so let's wire this up we're going to do i'm going to write this in a kind of a i don't want to say quick and dirty but a way that i wouldn't necessarily do it for production because i'd want to clean this up make it more generic make it um more uh repeatable and those kind of things but in our case we're going to create a simple application that just does the job you can work on making it more generic if you'd like i will um i'm not sure if i'll publish that or not but i will at some point but this is just going to be a simple application that gets the job done so let's create a let's create a couple of constants here the first one is going to be our connection string and we're going to hard code this right into our class i showed you in um having a better console app where we talked about adding things like eye configuration and logging and those kind of things that's what i'd probably do here at talk to configuration and create an app setting but i'm not going that in in depth here i'm just going to come over to my app settings i'm going to copy this string i'm going to paste it in here yes that's not ideal no you don't want that in your source control but that's what we're going to do for now const string hue name and this is going to be the person queue and then we're going to also have a static i q client that adds the using statement for azure service bus and call it q clients so those are the three that are outside of static void main because we're going to access those from a couple different spots now static void main itself we're going to um we're going to cr change that to async task main which you used to not be able to do this uh control die believed to add the using system.threading.tasks it used it not impossible to change static void main to an asynchronous caller you used to have to do a lot of hoops you'd jump through in order to make asynchronous calls using console applications no longer you can just change it to async task it's cool it'll work so let's get rid of this hello world and let's say that um q client equals new queue client and we're going to pass in our connection string and our cue name so this establishes the connection to our queue and we're gonna say var message handler options equals new message handler options we're going to pass in a um exception received handler object here or i'm sorry method we don't have that yet let's okay control dots and generate the method yes we can cool gotta love that that generates the method for us and then um we're gonna do we're also gonna have the end of this we have clear braces and we're going to say max concurrent cost what this is is a one what this says is that we're going to process one message at a time you could process multiple and if you have you know lots of uh processors lots of uh threading threads available to you that might be the case where you say hey you know we're gonna bump that up to 10 20 30 50. but for us we'll just do one at a time to keep it simple and then the other thing we're going to say is autocomplete equals false what autocomplete equals false will do but semicolon at the end here autocomplete equals false will not mark the message as complete so when we when it triggers and says here's a new message we're not going to just say and it's complete we're going to wait until we read the message and as long as they successfully read the message we're going to say yes complete this message and that's where that 30 second lock timer comes in where we have 30 seconds to do it before it gets unlocked and allowed to get pulled down by somebody else so that's our options and now we're going to say cueclient.register messagehandler and let's say process messages a sync that's a method name and we're gonna pass in our message handler options so where is this method ctrl dot to generate that method we don't have it yet and now at the end of this we're going to say console. uh let's do console.readline and afterwards we're going to say await q client dot close async so what this is doing is it's going to create a new queue client which talks to the message queue in the azure service bus a couple of options we talked about and it's going to register a message handler a message handler is the the method that's going to accept messages it's going to be be called when a new message comes in this is gonna just listen there it's gonna sit there and listen think of it kind of like an event handler you just registered an event handler and when the queue gets a message that triggers an event and it's going to trigger calling process message async so when a message comes in it's gonna get sent to this method and then we're gonna pass along these options so that's our register our event handler well register message handler now since that's going to be just right in the background there's not timer it's not anything you have to um call again it's like an event handler just waiting it's listening it's going to be told when messages come in because this is a console application remember that we start this curly brace and we end that curly brace so if we let this go then we register the message handler but immediately close the application we don't want that so let's rely on here that's going to wait until we hit the enter key once we do it's going to close down that q client it's going to close the connection to our azure service bus queue so it's going to sit here and just it's going to look like it's doing nothing in theory but then whenever a message comes in we're going to do some processing let's first tackle this exception received handler that's we passed in in our options this is where we say we had a problem somewhat wrong in our our message processing so we're gonna say console.writeline let's do our string interpolation and we'll say message handler exception and then let's just grab that exception message which is um the arg dot exception that's our exception that happened something went wrong okay it happens um and return task dot completed task so since this is asynchronous we're just gonna say we'd actually actually have to do anything so we didn't create a task therefore return a completed task to the exception received handler caller that's it you can go more in depth you can dig into this arg a little more and see all the stuff that's going on and all the different options but i think that's fine so now let's go to our our process message async let's call our variable something better so message is probably the best thing and then let's call this token this is where the work gets done so var json string equals encoding which is system.txt it's going to add that using statement at the top so there's our using statement right there on line three that just added encoding dot utf-8 let's look familiar get string message dot body so it's getting the body of the message it's going to get the string value out of it so it was you know as in utf-8 and it was a byte array now it's going to get converted back to a string which is a json string we're going to take it one step further which is person model which is going to add a using for sb shared dot models person model person equals json serializer which is from system.txt.json it's going to add that using statement dot deserialize where we talked about this and we're going to deseleze it into a person model and here's our json string so just to point out i did add that using statement up there now's a good time to compare your using statements against mine to make sure you have the same ones but now that i've deserialized it it's now a person object with that person object i can say uh console.writeline let's do our string interpolation a couple dollars or a couple of double quotes and say person received then our curry brace person dot first name and then a space and then our curly brace person dot last name so what this will do is it's gonna write out and say hey i actually see the person and there's our first and last name now that's not doing anything dramatic but this is where you would send that email out or you would update the database or you would you know do something else with this information in our case we're just saying right to the console that's it finally we're going to say await qclient dot complete async message dot system properties dot lock token remember that we said that um oh just a minute we um just say async that's an async method um so remember we said that we're up here we're not gonna auto complete well since we're not auto completing we have to say that we've completed the message so complete async we pass in the token the lock token whenever we have that 30 second lock we're passing that token in and saying the item that has this lock token that's what we have completed it's going to take that and say okay remove this message from the queue it's complete and once it's gone it's gone it's it's over it's it's not coming back with that that's it so we have our connection to the queue we have our options we registered that process sender message async so it's going to listen for changes and then once we're done we're just going to hit the enter key it's going to close out that cue connection let's run just the receiver so we're going to say set as startup project and run just the the console app portion it's going to open the wrong screen of notice it course received three messages one for tim cory one for sue storm one for bob smith we go back to our our service bus if we go back to the overview we'll see we have zero active messages they're gone because we have received them all we've we've processed them all now let's have some fun let's hit enter here and close the application out let's go to a solution right click on it and say um where is the set startup project there we go and in here let's set multiple projects let's start with the sender we're going to start we're going to move that to the top and then receiver will also start just start both the sender and the receiver so now we have our our application let's kind of shrink this down a little bit let's bring over our console application which notice there's nothing happening because there's nothing in the queue now on our sender now these two applications do not know about each other they have no relationship with each other yes they're in the same solution that doesn't mean anything they're two separate applications acting independently i say tim smith submit person received tim smith so we on the website we sent the message to the queue and on the console side we were alerted there's a new message we processed it and displayed the information so sue corey and over here actually enter sue corey shows up bob cory bob corey tim storm tim storm so now let's process them one at a time and it keeps doing that so that our cues we hit refresh here there's still no active messages because they keep getting processed but if we had some kind of maintenance issue where we shut down our console application but our website was still running and we said tim corey and we said sue smith and we said bob corey we said uh sue oh last name is required sue storm again we sending messages and they're just piling up no worries once we restart our applications or once you get that other one running it's gonna process all those messages and we're still ready to process even more um like so so that is how you use azure service bus for both sending messages to the queue and also receiving messages from the queue this is a really powerful topic and one that is critical to know if you are interested in microservices and it's really important to think about how you can use this even if you're not gung-ho going gonna do tons of microservices which i don't encourage the let's make everything a microservice but i do encourage that we have a massive monolith let's break a piece off and make it a micro service that we can be more flexible not a thousand micro services but let's start pulling chunks off and reducing our our complexity in one application and allowing for much easier maintenance and easier uh ways of handling these things and that's where these cues will really come in handy now just to finish up what i would do since you've seen my password i'd go back to my service bus itself go to policies click on root manager and i would go the ellipsis and say regenerate primary keys to wipe that out but since i am done my demo i'm going to go to the resource group see the link right here and i'm going to say delete resource group which only has one thing in it it's going to delete that item as well i copy the name i paste it in i hit delete it'll take a little bit but this will delete the service bus first and then it will delete the resource group as well that ensures that i'm not gonna get charged that incredibly exorbitant five cents per month for my azure service bus which is a good thing though because i'd otherwise forget about it and yeah it's only five cents a month but that kind of stuff well maybe that doesn't add up but um you know things like sql databases or web applications and other things can add up over time so make sure you're cleaning your stuff out so you don't accidentally use your credits when you don't need to okay that's the the demo that's how we use azure service bus i love to know your your questions what are the things that you're wondering about how to do have you try it out have you got my source code try it out and have more questions afterwards let me know down in the comments let me know as well what other things in azure you'd like to see me cover because there's a lot of stuff that's really great in azure that can really make your life easier both in doing things for development mode azure is great for development mode it allows you to do a lot of stuff where you don't have to have this massive machine you can do everything in the cloud but it's also great for production and you can really do some really cool things without having to break the budget either so what questions do you have around that or what other topics do you want to see me cover leave those down in the comments as well as you know how you enjoy this video and i really appreciate if you could give this video a thumbs up um that helps share this video around obviously if you share on your social media that'd be even better um but this way it it tells youtube that yes this was a great video and that yes you're interested in having more people like you see this video so thanks for watching and as always i am tim cory [Music] [Applause] you
Info
Channel: IAmTimCorey
Views: 46,899
Rating: undefined out of 5
Keywords: .net, C#, Visual Studio, code, programming, tutorial, training, how to, tim corey, C# training, C# tutorial, asp.net, .net core, asp.net mvc, azure service bus, azure service bus tutorial, azure service bus queue vs topic, how to use service bus, azure serivce bus tutorial with example for beginners, azure service bus queue
Id: v52yC9kq0Yg
Channel Id: undefined
Length: 76min 36sec (4596 seconds)
Published: Mon Dec 21 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.