microservices are an increasingly popular software architecture style that structures applications as a
collection of highly maintainable loosely coupled and independent services each typically owned by a small team
if you are wondering if you can use the.net platform to build microservices or if you have perhaps been asked to
start building them in your company it is worth checking out the multiple existing and new features
that that net5 offers today and that you can use to your advantage as you drive towards building resilient
microservices with a minimal amount of code so let's get started in this video you will
learn how to create a.net 5 microservice from scratch
how to build and debug a.net5 project in visual studio code how to interact with your microservice
endpoints via open api and postman how to keep a configuration
and secrets separate from your service code how to simplify your http requests to
external endpoints how to deal with transient errors on external services
how to report the health of the service and its dependencies and how to produce logs suited for a
micro service environment
to follow this video step by step you will need a few things first the net sdk which includes
all the tools required to build your.net 5 apps
visual studio code which we will use as our code editor so to edit build and
debug our service postman which is a very handy tool to
interact with the service endpoints and finally some basic understanding of the c-sharp language
to get started we are going to use the.net cli or command line interface for this i will
be using the windows terminal but feel free to use a simple command prompt powershell window
or whichever terminal you are mostly comfortable with and then being in the terminal what we
can do to create our micro service project is actually use the web api template so to do that let's do net new web api
hello net5 that's going to be our output directory and then i'm also going to specify the
no https flag now the reason to disable https with this flag
is to keep things simple and also because in a micro service architecture ssl is a concern usually delegated to
infrastructure components like an api gateway so that the microservice can safely avoid dealing with it
however feel free to skip the no https flag if you rather use https from the start
so i'm going to hit enter here and that's going to generate our files for our project
so i'm going to just switch there and now i'm going to be switching to
visual studio code to do that i'll just type code dot
and here we are in the visual studio code interface now the first thing the visual studio code usually do in as soon as you start
one of these dotnet projects is to offer you to add a few files and we're going to say yes and we're
going to explore what those files are about this file here describes how visual studio code is going to
run a series of tasks for us for for whichever task we need to execute here and the main one is going to be the
build task so this says here okay so we are going to have a task called build that's going to run the dotnet command
uh which is a process and the argument for that command are so it's build because dotnet build and then here's the project
that you have to build and then here's a couple of other properties that you want to pass to the building gene
the other thing that i wanted to mention is launch.json so this is the this is the file that describes really
how we're going to launch uh this project from the vs visual studio code perspective
and what this describes is that uh the pre-launch task for for for launch
is built which is the one that we just saw here you see we said build so we have to anytime you're going to
launch this project you first have to build it and then you're going to be running the the program that's up
over here so this is the location where our dll will be generated and also when uh when the host is ready
when it says yeah i'm ready to go uh this is uh it is supposed to open a browser
uh so that it browses to the location of the host this is well also where we describe the the asp.net core environment the
where we are in right now so this is why it knows that we are in development environment and not in production so now that we have done that what we
can try doing is first let's build this project and you can do that by going to terminal
run build task built so this opens the integrated terminal in visual studio code
and boom it has been built and now that it's filled uh we can go ahead and run it so to run
it uh i'm going to click here i'm going to say start debugging in this debug hub
to see better perhaps i can expand it yeah then the core launch so just run this
it's going to build it and now we're opening the browser and
here we are now the default url that we have configured right now read is not pointing anywhere so if you want
to actually see something what you can try is just going to the swagger url and this is going to take you to the
swagger ui or the or the open api specification that we talked about before so here is where you can start
uh testing your api so if you click let's say on get is the
only thing that we have defined so far so get for weather forecast
here you can see a description of this api and you can actually try it out you click here i just hit execute
you're going to see that swagger swagger ui uh and generates a comma that will be
needed here's the request url and here's the what the output that we got as you can see it's just a
simulated objects based on what we have right now in the controller
now one thing uh one kind of a tip that i have in this case i'm just going to close this is uh how do we
build this uh more quicker for future iterations uh like one thing to consider is that
you can just do ctrl shift b uh to open this this build task window
here right so that speeds up things a bit uh but to really
make it even easier what you can do is in uh let's go back to
uh that's adjacent here you can add just a little segment here just three lines i think uh
which is uh the group so this grouping field here allows us to specify that this is
going to be the default task so build becomes a default task when you do the uh when you do the you run the
build test from the terminal menus if you say now terminal and run build task it will go ahead and just build it will not pop up the build
window anymore and if you do ctrl shift b the same thing would just go ahead and build
okay now you notice that when we started the project it did not just go to the swagger page it actually had
trouble getting there and this is and that is why we're missing a little bit of a configuration
here in sorry launch settings launch.json so here i'm going to close
this and so in order to tell visual studio code where you want to start when you launch
you just have to add this uri format section here in server ready action where we're saying that wherever the
whole support it is just append a slash swagger to the url and that will that will be
good enough so again we go to the backhop and you click here you can also use type f5 by the way
and will be the same thing now we run opposite browser and we are right there
in the swagger ui so now this is this is nice uh to try
out the the apis uh but eventually i uh find that uh there's uh other tooling that it can
become uh pretty much more handy uh to test the apis and this is because you may not want to be open in a browser every
single time that you just change the code in your app so to do that let's open up the postman
the postman program
so here we are in postman and like i said pogba is a tool that you can use to query any api that you have available
really anywhere so what i'm going to do is just go back to the browser and let's remember what which was
that um that url just hit execute again here it is this is the request url so
i'm just going to take that and i'm going to create a new request in postman a get request
i'll just put my url and i'll hit send and as you can see we have the
the response right here so the nice thing about postman is that we will be able to start creating a bunch of
requests here without having to worry about opening browsers to test the apis
and if you're going to do that let me actually just stop this what we may want to do is just
to actually prevent opening browsers all the time so i'm just going to be i'll just remove this from here so no
more browsers open for vs code i'll hit f5 the only thing that i'm going to get is
this prompt here that says yeah we're listening in that port but then i can just switch postman hit
send and now we get my results so i will not be dealing with browsers anymore since i'm working on a microservice
web api kind anyways so to make things a bit more interesting
and since we're trying to create a microservice and want to showcase a few of the nice things that we have available now
with dotnet5 what i thought we could do is just bring this project a little bit more into reality
so what if we can just change this project and make it actually query some weather information
uh perhaps from some external service so that we can actually tell the weather of some city right uh so to
do that what we can do is just take advantage of a service called open weather so i'm
going to go to this page now it's called
openweathermap.org and here sure let's allow location
this service allows you to query a bunch of apis several of them that are free
but you can use just query query weather data so for instance if we go to this api here
you can see that you can use this to create the weather to create the weather for some city and as long as you have a an
api key available so the api key is the way that the service identifies you
so the first thing that we're going to need here is to actually get an api key so to do that i'm going
to hit there uh here is where you're going to need to create an account it's it's totally free
and i already created mine so i'm going to go to my account
all right there it is and uh you will get i think you'll get a
one key by default this is what i found the first time that i came here but you can create as many api keys as as you
need so i'm going to copy my api key actually not copied yet uh let's let's look back
at the api over here uh so let's actually test out this api uh since we have postman
available how would this api look like so i'm going to go back
to our page i'm just going to close swagger i'm actually also going to stop this code and i'm
going to go back to postman so i'm going to open another tab here and i'm just going to paste what we just
found and then i'm going to put https here this is an 80 ps api
and uh we want to query data for some city one of the closest cities to me a
very nice city very nice city is seattle so let's do seattle and here's where you will paste that
api key so i'm going to go back to the open weather page i'm going to copy this api key
and i'm going to paste it right here and then i'm going to be hitting sent
and here it is we have some
information about the weather of seattle as of right now and they're really the most meaningful
pieces here are this kind of a description of the of the
weather and not surprisingly it's raining in seattle um then we have the temperature
and this temperature is actually in a bit of a different measurement that you would expect so
what we're going to do is just change this little bit so that we can append
units equals metric so that's going to give us the weather in celsius
uh let me hit send let's see yep that makes sense
it's pretty pretty cool right now around here and we're choosing celsius just because
uh to play around with that with these objects that are already been generated for weather in the in that project right and the last one that we're going
to pay attention here is the dt which represents the current time
i mean or the time of the calculation of this weather information
okay so now that we have this how do we integrate uh how do we call this api from our from our microservice
so to do that let's go back to the project uh the first thing that we're going to need
is to actually specify i mean there are two interesting pieces from the name that api
which are uh the endpoint i mean the location of this api that we need to call and the other
interesting piece is going to be the the api key so this we are going to
treat as configuration as you should do in any microservice you should not just hard code these pieces of data
you want to set it in such a way that you could change them anyway without having to really touch
the application so how can we bring that in let's go back to the
project i'm just actually going to close all this stuff and what we're going to do is we're going to create a a class
that's going to represent that information in the project so to do that i'm just going to say
new file and we're going to call this service settings
so let's put just let's put it in the same space as everything else which would be
hello.5 and let's do a our class which is named service
settings and here we're going to add uh a couple of properties
right the first property is going to be uh
let's call it open weather host and let's add a second one called
uh api key okay so we have these two
properties now uh and yeah so this is going to represent the host uh just
api openwaremap.org and the other one's going to represent the key now how do we let's look first at the
host so open weather host so this is something that we should be able to safely configure
for our application outside of the of the actual code uh so that's where we can actually take advantage of app
settings json so what i'm going to do is just add one section here
we should have ideally should have the same name of this service settings class so i'm just going to
copy this so we're going to call it service okay
and here we are going to have uh those same two pro well actually just open
water host we don't want to put an api key here and yeah you could but we don't want to
store secrets over here that's kind of a bad practice so the host is going to be
like we said api openwaremap.org and that's going to be our configuration
for the host now what do we do about the key so we don't want to just type it here so you should never ever
type or hard code a lever and even worse checking secrets into your git repository so to
avoid that what we can do is take advantage of this thing called the net secret manager so this is a tool
that you can use to safely store secrets in just for your development purposes not for anything out of your box
and we'll just keep the secrets outside of the completely outside of the project but still be available for for your app
when you run it in order to do that let me actually open the terminal
open the terminal here this is a partial terminal and what i'm going to do is first what
we have to do is do dotnet a user secrets init
so this initializes secrets for this project and if you actually go back to
the project you're going to see that we have a user secret id this was just added
represents the identifier of the secrets of this project now that we have that what we can do is
dotnet user secrets set and here we have to
name the secret that we want we i mean we get a name and a value the name should be in such a way that it
matches the class that we've been preparing for this in this case we create we created this class called service settings
so we'll name it service settings we'll do a colon and then we'll do api key
so this is a way to set a configuration based on the convention that.net knows
about so for this hierarchy where we have several settings an api key and we can totally configure a a
set configuration named as service settings called api key and if we had even more nesting
here like if the api key was a compound property and it has even more properties you could just keep adding columns here
for keep to keep nesting uh these secrets now that's the key and
then let's get the value for that so let's get that from postman
in this case yep that should be our bi key
here hit enter and now the secret has been stored uh in the in the secret store right so
it has nothing to do with the project at this point is just store somewhere in the box
i'm going to close this terminal here so now what we want to do is to tell
the to tell our app how to register these secrets
into it and for that we're going to do exactly that so we're going to register
that configuration that you can do by again using the services collection in startup configure
services so you can say services configure and here you are going to specify the
type that we created service settings
and then just to keep this thing simple we're going to say okay so now from the configuration object
this is the configuration property that we have right here from that object get the section named
just same as the class so the class is uh service settings just find a section that's named as
service settings which happens to be the section that we declare here service settings that's why it's good to
keep the same name so just by doing this we have uh i mean as soon as the app
loads uh the configuration engine we're going it's going to find configurations both in app settings json
and in the secret store uh that are going to be a populated into an instance of service settings
that's going to be registered here in the dependency injection engine of of
the net 5. so by doing this we are going to be able to access this configuration anywhere we
need it in the application which is printed now how where do we actually write the code to
access the api so to do that what we can do is create a what we call a client a service
client this is something supported by the i http client factory uh
object objects internet five and what we're going to do is just
create a brand new file here we're going to call weatherclient
same namespace and then we're going to create the class
weather climb now here in weather client we're going to need a couple of things and at this
point i'm actually going to start copy pasting a few a bit of more code to avoid so much typing here
two things an http client object and the service as every setting subject and i'm actually going to bring name
spaces here http client is the object kind of the key object that you would use in any
net app to access external endpoints right like the one that we need to call right now so we are going to need those
two properties also yeah like i said a settings instance where we're going to retrieve this settings information
now we're going to add is a constructor in this case uh yeah with
our client and again here we are doing dependency injection right
so we are injecting an instance of http client that's going to come somehow is going to be constructor
constructed in startup and is going to be available for us over here without us having to worry about
how to build it and also this i options object which is how you are able to receive the
configuration that has been registered right here so we here we configure service settings now we receive a iop we receive an
ioptions instance here of type service settings which by the way i'm going to
add a new space and then we just grab both of them into our
properties http client options has a property called value and value is the one that actually has the
service settings that we care about next thing to do is to uh have some sort of
representation or type representation of that api that we saw before so i'm going back to postman here and here
we can see sorry we can see that if we wanted to get those elements that we talked about we
would at least before.net 5 we will need to create a bunch of types since you see there's a
bunch of quite a bit of composition here so it's not just a flat object so we need some weather object here
which will have description and the description that we are inserted in we will need this main
a class with the temperature and then we would need yeah just a property for the or a field
for the for the time uh so yeah before than the five you will need to create at least a couple of
classes or or two or three classes for all this stuff but luckily in 205 there's this new thing called
record types so record types is a new way for you to declare this kind of
objects in a kind of an immutable way and with with a nice addition of how you can compare
these objects not by reference but by value but it also has a very nice syntax that can simplify
a bunch of scenarios like in this case instead of having to create a bunch of classes here's what we can do
so first we know that we need a weather class so let's see we well we need a weather
object right where we need to have a description inside it all we can do is just say all right so
i'm going to declare a record the record type
we're going to name weather and that weather is going to have a description and that's it
that represents that entire weather object or that weather section that we
have here okay and which by the way is an array is not just one object but we will need
instances of where next one is main so from main we will need a property named temp
so to do that let's go back here and just like we did with weather let's declare public record
main so like like we said we need a temperature we will use decimal for this
so decimal called and just like that we now have uh we have
that main structure right there as a record finally uh we're going to create our overall uh
a record that has all the properties so let's call it let's just call it
forecast for lack of a better name and this forecast just like we saw needs
to have a collection of weather objects an array of wired objects the main object and the the time
so let's see we're going to say okay so this is a wet array
we need an instance of main and let's use long for that date time
and that's it so here's the entire representation of the of the interesting pieces for us
from that response of the api so no need to create a bunch of classes for this anymore
now where do we actually do the call where do we retrieve that weather information so to
do that we're going to just introduce a new method let's call it and i'm going to do a bit of copy
pasting here so this is going to be an amazing method
and i'm going to import a few missing a spaces here i guess just one mini space uh async
method called get current weather async is going to receive a city so we pride a city and it should return one of these
forecast objects and in order to be able to actually do the query what we're going
to say is uh so let's see forecast is going to be
a we're going to use the http client object and um interestingly in starting with
net5 we now have very handy methods for both retrieving information we're
retrieving and posting information but also doing the serialization and deserialization for us in a very nice way
so we just need to do in this case get from sorry get from
json async and i'm going to add a missing name space here systemnet http so this is the
the namespace that has the new additions in.5 for this kind of query and here's where
we would paste the actual url right so i'm going to grab that url from from here
i'm going to paste it here yeah all hardcore now
how do we fix this so let's first we have to wait on this because it's an async call
okay now next thing we're missing here of
course is the type so what are we going to deserialize into in this case it is a forecast object the one that well a forecast
record object record type and now here we just have to do a bunch of replacements because we do
have that settings object just waiting for us over there we're going to do is do a little
bit of a string interpolation so that we can introduce uh whatever is is
should be parametrized here just going to open curly braces here i'm going to say so this is services
it is sorry it is uh what's the name settings just settings settings that
open weather host and then the other piece is here we don't want to use hardcode cd
we want to use the city parameter and for the app id
we want to switch to dot api key and then we leave the meta
units as asthmatic that's just fine so with that we should be able to just
retrieve that forecast information just one line uh simplified by the additions in 2.05
and so after having that forecast object we can just do
return return forecast and that's it we have a winner client
that is able to go ahead and retrieve weather information based on some city now
just as with anything else this was reclined and needs to be registered into the series of services
available in our application so to do that we're going to go back to startup
and in startup we are going to go to configure services and we just have to say
services.httpclient i will say weather client
and that's it so that will take care of registering the this r class into the services
collection and that net five will know that it needs to inject an http client object into that class so
that we can do the actual calls to the other service
now that we have this uh well it's time to actually touch our controller and to make it a
real controller that can actually receive a city and return the weather for that city so to do that
we're going to do just a few things first let's get rid of all these run the random set of summaries
we're going to need to again inject an instance of that weather client so whether client
client here it is and then let's let's use a little bit of
intelligence here create an assign field client so that's going to go ahead and just generate you see generated a private field for me
and assign it from the client parameter right there ah yeah one thing
we're missing here is the
the access modifier so this should be public so we can actually use it on the on the other side
and we're missing one more thing service settings should be also let's
forgot that there it is okay so going back to the
controller now we have our client available and now we're going to change this get method here
so that first thing is that we're going to modify the route so so we're going to add here uh
where is it uh route attribute and we're going to say
that we're going to receive here uh sorry let me just copy that one over
there keep it simple
and we're going to receive a parameter here that's going to be the c so now we're modifying it in such a
way that we're saying hey so the route is not just going to be a wetter and now you're expected to
provide some city here like i say cl right that's going to be part of the route right so we're just
kind of describing how we want to our route to look like and then that city we're going to receive here
okay now we're not going to be returning a list of weather forecast anymore it's just one forecast for the current
forecast for the city that has been specified
and now uh yeah we can remove all this stuff and what we can do is say so
forecast bar forecast say equals um actually we have to turn this
into an async method because we're going to be calling another using method so this is an async task of weather
forecast so we have to say await and then we have
our client so we'll say client dot get golden weather async
and we'll give the city that should give us the forecast and
then finally what we have to do is to turn this forecast object that we got here
which is really a record object into the weather forecast dto that the app is already using so to
do that let's use to return new weather forecast and then we'll do
so the summary is going to be forecast that
winners let's take a closer look at this uh so says weathers here but it's really
just uh one weather object so i'm just going to rename to weather that's how
it shows here even if it's an array it's just named weather so we have to
honor that so i'm going to say where there of that collection we want
index 0 and from that one we use one description next one is the temperature in
centigrade it's going to be forecast main temp
although we have to convert this into an int to match into that contract that we have
and finally the date that date is actually in a kind of is kind of a unix-based
time set so what we're going to do is uh data the time of set
from unix time seconds forecast t
dot day time uh time yeah that should do it
yep so let's see are we missing something
that so let's try to build this um it builds i'm going to do f5 here
to run it and so it starts now let's let's go back to postman and
so we're going back to our api it is not anymore just weather forecast we have to specify the city right so let's
again let's do the seattle sample here see what happens
boom here it is yeah still very cold in seattle so but yeah i mean we we got it i mean
we are going we go ahead as soon as and in fact we can explore that a little bit of a
breakpoint to make it more interesting i'll put a breakpoint right here
and so we keep going through this method so let's see
cursor yeah come here we got the weather object and
let's put a breakpoint back in the controller over here i'll just do f5 so we come back here we
have the weather forecast object and then then we just do the transformation and we return that weather forecast object over here
and so that worked that's that's great now one of the things about microservices is
that we want to make sure that they are reliable so as reliable as they can all the time and as by introducing this
external dependency uh this weather open weather service uh now we have kind of a point of failure so what
happens if that service goes down so what does what does that mean for our service can we keep up our availability there
so let's see what happens what am i going to do here uh it's pretty much the only way that i
know to test this scenario is to just disable my internet temporarily
and i'm going to hit send again see what happens uh yeah after i have a breakpoint i'm
going to remove these breakpoints now hit run
and boom no such host is known so yeah we can't talk to it there's no internet so now our service is down
so this is exactly what we don't want to have an error to our microservices so one way to start dealing with this uh
one first approach we can do is well let's do some retries because it potentially can be a transient issue
which happens all the time in the cloud so how can we introduce some retries to this
so let's go back first i'm going to re-enable i call it the internet because we'll need it for the next step
and i'm going to go back to our app so i'm going to stop it
so what i'm going to do now is i'm actually just going to close all this stuff go back to the project and actually
going to go to open the terminal and i'm going to up add a new nuget package
so to add a nuget package to your project you have to say net package and in this case it's called
microsoft extensions http poly so poly is a pretty popular
package has been around for a while and it allows you to do a bunch of a transient
error policies where you can specify how you want these errors to be handled and to do
that what we're going to do is go back to startup so we don't have to actually modify the entire uh
project to do retries here and there i mean like you could say you could think that you may need to go to weather client and do
some sort of retry here what if this guy fails so try catch and stuff like that but actually we can keep things simpler than
that what we're going to do is this
so let's see just copy pasting again yeah
so add transient http error policy
uh we are appending this to our http client class this is a facility of the a i
um what was the name the ihtp client
builder uh where we can introduce a policy so i'm going to actually fix this using poly
so we have the writing spaces yes so this is a transient error policy where
we or we are saying that the policy is a wait and retry policy
is going to retry 10 times so that's the police let's retry it 10
times and let's see on each retry attempt it is
going to sleep as much as what this expression specifies now this is what we call
exponential back off in this case it means that the first time it is going to uh
it is going to slip for uh two uh reset to retry attempt seconds so
retry time is going to be one first time is just one so two raise it at a one so if that after that retry we fail
again i mean after that sleep will fail again and then we're going to wait two raised
at two right and then two raised at three two raised at four so it's exponential so each time we uh
wait a little bit more and this is just to add a little bit of uh uh i mean changing behavior to those retries so
just not keep retrying at the very same interval every single time uh potentially overwhelming the
service the services is on the other side so let's give it a shot so this should
allow us to do some retries so what i'm going to do is again disable network
and run this f5
so back here i'm going to hit send just waiting there it's not just failing
now and as you can see if i can expand this uh we're trying so
we're doing a get we did already two gets here get get and they will probably come
more gets you see get get get just it just keeps trying just expands the the sleep the sleep seconds a bit more
and a bit more and if i just fix my network connection now so i'll enable this
yeah it may take a little bit but eventually we should get a successful lighting it
already did it let's go back to postman so yeah there it is success so without having to touch
really any anything other than that little piece in startup over here now we have retries for our
microserves which is pretty neat now the other thing to consider
is that so that's nice but what if the services is really going
to be down for a while and we don't know and we don't want to be really
overwhelming that other service and just having our clients wait forever and there so to for that there's this other
technique called the circuit breaker and that i want to show you here so i'm going to stop this
and the secret breaker is going to allow us to uh introduce a behavior so that we will
only retry so many times after which we do something that we call the open the circuit and then no more
uh tries are going to keep happening until some other condition happens so in this case
let me just add this uh let's see just appending to the same
sentence so one more transit a transient http error policy called circuit breaker
so this means that uh we will try we will allow it to retry
yeah three times so we will retry it three times if after three times we keep failing we
just can't get a successful result then we're going to just open the circuit
and then no more requests are going out so we'll just fill fail fast fill right away right so that
way we avoid overwhelming the other servant and we and we return fast to our clients which in this case is much better than
just keep them waiting forever and then uh that circuit is going to
stay open for in this case uh 15 seconds let's actually reduce it a bit 10 seconds
and then after those 10 seconds it will try again see if it succeeds if it doesn't it just opens again it
just keeps open and then we enter into that cycle again so let's see how that uh how that works
so i'm going to again disable the internet run this
okay so go to postman hit send let's see what happens behind the scenes
so it is trying try it a couple of times or perhaps
already three times so give it a moment and then
yeah if i go back to postman here it is secret is now open and it is not
allowing any more calls so no such host is known if i try again let's see what happens
so yeah secret open and then now we're getting fairly fast results here as you can see
it's not really waiting so the circuit is open it will be open for about 15 seconds it notices that
it tried again it didn't succeed so it just stays open so now let's fix that enter the internet
label that and then yeah again it will take a while but
eventually this circuit is going to yeah there it is so you could close i'm going to try it again and notice that it
succeeded close circuit and then we're back into good shape so pretty handy
and pretty common approach when you have to deal with external dependencies in your microservice
now so this is this is good but is there a way where we can be a bit more proactive with this so we actually need to wait
for our clients to be hitting these these situations and causing reliability uh to them so can we
actually detect this situation before it happens so it turns to be that yeah there's a way and there's this thing
for this is this thing that we call health checks so health check is a way for your app to have an
endpoint where anybody else from the outside can query for the health of the service and typically this would be your
orchestrator system right let's say cornelius that system will be pinging this health endpoint and to check
how we're doing let's see how we can enable a health check for this app here
going back to configure services it is as simple as doing this
adult checks so that registers the health checks uh types into
our app and now we have to we also have to update our middlewares here we have to induce endpoints we have to
map health checks right so this is this adds the routes for checking health so let's do
you can name this anyway i'm just choosing health it's a pretty common name some people would do health c or you
could do hc whichever works best for you and that's it really i'll hit f5 again
so let's go back to postman and now what we want to do is to actually
i'll just grab the the base host so i'm opening another tab here another
get request now i'm going to do health hit sent healthy
so this means okay so service is saying yeah we are all good now what happens if i uh disable the
internet so disabled let's try again send and interestingly we keep getting
healthy so this is a good point because even when our service is up and running which is
great uh the dependencies of the service in this case the external service is is down so this is exactly one of these things
that we want to detect be a health check right so to do that
what we're going to do is uh let's go back to the project and stop this and what we can do is create what we
call an a health check uh it's just a class that implements i health check where we can do these
additional checks so let's add that so let's call it external and point
check all right so i'm going to grab that name and then it's our namespace
a hello.net 5. and then let's do a class let's make it
public yeah the external endpoint health check this class has to implement
i held check type and
uh as per doing that it has let's let's actually implement the interface right there
and what we're going to need since what we need to do is verify i mean the way that we can verify this
is just by doing a very simple ping right into that open open weather
endpoint so for that we're going to need that those uh service settings again so we're going to
need to inject those into our constructor so let's add a constructor for this class actually and just like we did before we use the
eye options pattern to receive those options and to inject it into this this class
and we are going to add a property here too we can actually
just generate that so let me do this uh we'll say green and sign field
options we don't actually want the options we just want the service settings so let's
let's do that settings so this dot settings equals options like
that there it okay and now we have to implement a check helsing
he'll check held async and so yeah for that again i'm just
going to grab a little bit of implementation from here
and let's see what this means so i do have to import a few types so basically
pink is available in system net network information and
here i wanted to show you one also one new thing.net five which is uh this way of declaring a new type
so usually uh before that five you'll have to do well ping ping equals new pink but since
this is a bit redundant uh because yeah i mean what would i be creating if it's not an instance of pink
you can just avoid that stuff and you can say equals new and that's all it is you get a new type
so just a bit of simplification so i appreciate it from the n5
now next thing let's let me add yeah so this method should be async
otherwise how are we going to do an async call and what we're doing here is very simple so as you can tell sent being async
and then we are taking advantage of the open weather host that's available in settings we ping that we get a reply it reply is
not successful we say hey this is unhealthy otherwise it is a healthy result
and then we're going to return a healthy resolver there yep so that's our
external endpoint health check and what we have to do now is to actually register
that health check with our app so to do that we're going to expand this add health
checks with sorry with
a check and in that check we're going to add external and point health check the
classes we just created we need to give it a name so we'll name it just as
like the right name will probably be open weather you can use any name here and you can
you can imagine that as you introduce more dependencies you will just keep adding checks here right so for
your database for your service broker uh for um i don't know any other
service that you may need to query outside of your own right in our case it's just open waiter for now it's good enough
and just by doing that we have health checks let's see f5 again
so back to postman and i think we don't have network right now yeah we don't have it so let's check health sent
and boom unhealthy because a health check is telling us now
if we re-enable internet again
we should get hopefully healthy health it is yep so like i said
so this endpoint will become key to whichever monitor or orchestrator system
is trying to make sure that your service is up and running so that we can detect that situation
fire some alert and do something about it before our customers start hitting our microservice and hitting this this problem
now one last thing that i wanted to show you that's uh fairly kind of useful in terms of microservices
and that's enabled by dotnet five is uh the way that we present logging
right so let's see so usually let me at least stop and
start this again uh normally the way that you you see the locks are like this
right so this is kind of structured logging that's what we can start glowing so each of these lines
is kind of an object that represents the the level of the log who is emitting that that lock and then
what the actual log is right so that's that's what it shows there but in a micro service architecture is is
not very uncommon to want to i mean the recommendation is that
you just log everything into your console that a typical approach is logged into
the console and there will be some infrastructure pieces in your deployed environment
uh that are going to take logs from that a console output and they're going to be probably
transformed and then eventually sent to some login backend right so there's a
bit of decoupling between you producing the locks and those locks being collected in some other bag right it's very
different than than like more of a uh legacy or monolithic systems where you will just
log to some file or to some location it's really not like that you just log to the output and then
somehow that output is being transformed into logs eventually however to make that happen uh this kind of
structured login that we're doing that we're seeing here is not really useful right for for machine it's not machine readable really
it's human friendly but not machine readable so what we really want to have here is json json output
how can we get json output here so it's actually very very straightforward with a new edition of net five
and what we're going to do is just close this and go back to program cs and here we're going to expand uh
the the way that we configure the host so we're going to say hey let's also configure login
as we configure login we're going to receive a couple of parameters the context sorry context and
logging and we're going to get a lambda expression here
where we can do stuff right so here we're going to we one thing we
can do is just say hey so we're going to do login.json console the json console
is a new console available uh alongside all the other login providers uh in in.net available
now in dotnet5 so just by doing this and we hit f5 you'll see that the logs will now also
show up as json so let's see so this is the structure login version i mean the the simple
console version of logs and here is the json version of the same log as you can
see which will be machine readable by by the login infrastructure in a microservice
architecture and so yeah that's kind of what we want however now it's it has become actually
a bit super noisy for us so we can't really tell much of what's going on here so one thing that i like to do is to
just have a bit of a variation here so depending on the on the development depending on the environment
either use the simple login or use the json log for this so one thing that you can do is
since we have uh the hosting environment cycle available in this context object here
what you can do is something like this let me add to this do a little bit of copy pasting again here
there so here we're saying hey so only if the hosting environment is
production go ahead and remove the simple console and then add the json console and that's and that's
it so now if we run again we're going we'll just back into the simple console
because we are in development environment but if we were in production this would have turned into
json so i hope this was useful and if you have any questions or if there's
something else that you'd like to see in this channel please leave me a note below uh consider
hitting the like button if you're getting any value out of this and don't forget to subscribe if you'd like to know
right away when i publish any new videos thanks for watching and see you next time
No comments:
Post a Comment