.NET 6 - Web API Caching with Redis ⏲🌐

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
foreign thank you for watching this video I am Muhammad and today we're gonna be discussing something really interesting regarding performance of our web API we're going to see how we can actually Implement redis and caching in order for us to boost the performance of our API we're gonna go through the theory of caching and basically why do we need the different types of cache that exist and then we're going to be seeing how we can actually Implement all of that inside our dotnet sex web API so if you like this video please like share and subscribe it will really help the channel as well if you'd like to support me yeah please try please consider supporting me on patreon or buying me a coffee if you support me on patreon you'll be able to get access to all of the source code so now without further Ado grab your cup of coffee and let's get started in order for us to know if our API is actually performant and it's actually delivered the level of performance that our application requires there's multiple ways that we can actually Implement in order for us to achieve this performance and one of these ways is actually caching and by caching here we mean by actually caching the response we're gonna go through this video first by actually going through the theory of caching see how actually we can implement it see that all it can play and how it actually can Elevate some of the processing power that our API needs to do and basically have a much more faster response time and effort to uh whenever a user is trying to do any calls so without further Ado let's check right now uh what caching is and how we can actually start implementing in our not application on web apis so as we can see here this is the normal process when it comes to an API request so we have a client which actually doing a quarter application let's say it's going to get a list of something the applications can receive this response once the application actually received this response it's gonna send the request to the database the database cannot do that query on the data prepare the data send it back to the application the application will verify it and once that is done it's going to ship it off to the user so we can see here that we have basically one two three four steps and basically we have multiple intermediary in order for us to get this data so the client will go through the server the server will get it from the database and then the Flowback is going to be similar so from the database to the application to the client and that's fine if for example you're working with a like a medium application we don't really have you don't really have time sensitive information that you need to get so you don't really need a millisecond approach that you need to achieve and all of that so but in case you have that high performance requirement this model is not really feasible and this model is not really uh gonna give you that millisecond response time that you're going to be needing because uh although that client is actually doing calls to the server the server is doing course in the database and that's going to be another bottleneck because from one connection to another from one connection to another and there we can see where the bottleneck lies but what we can do actually right now is let's see another implementation with an uh with actually caching in place so within this implementation we're going to be taking the same approach as before a client decide to get a list of some things from the server the server is going to receive this request it's going to process this information once this information is being processed as it should be it's going to go to the database database can do that query on the database on the data once the data is available it's going to send it back to the application the extra level here is we're copying the data whatever of the database has returned we're putting it inside the cache and basically a cache here is like a temporary storage and that means that this data that we just received from the database it's going to live inside this cache it's the temporary stories that we're going to have it's going to have an expiry time and basically once that data is there we can actually reutilize this data instead of actually going back to the database and that basically elevates the requirement for us to go to the database do that query execute the query it could be a very complicated equity for all we know and getting back the result that way the results is already available for us directly from the cache and once the application actually save the data into the cache what it does is basically send it back to the client and once it's back to the client the data is there so how will this help us so let's say after for example 10 seconds the user requests this data I can so what's going to happen in that scenario in that scenario in case the data actually uh in the database is the entire cache story is valid the client will do the request to the server the server is going to receive this request it's going to check in the K in the cache it's going to say okay I have this data and the cache it's actually valid within the actual time frame that I need because it's valid within the time frame and that I need I can reutilize this and basically here we can see that the response came back to the service from the cache actually from not from the database and once it came back to the application from here what did it do it actually came back to that client and send back the response and we can see through this example here that we have actually removed the database integration completely for that request because that data that we needed from the database is already being cached inside our basically is already being sorted inside our cache and we can actually utilize it from there rather than actually going through the full process of going to the database executing the query and then getting back the information and sending it back to the user because even the data that we're storing in the cache it's already fully processed so at what already verified it in the right format we have already created the right response type that we want to send back to the user so it's already ready for us we don't really need to do any further modification on the data all we need is just grab and send back so for this reason here we can see that the database is actually providing us with sorry the cache is already providing us with a lot of good functionalities and here what we're going to be implementing within today's video is we're going to be seeing in how we can actually create a web API the.net6 we're going to basically create a database a random database and have a table there and then what we're going to be doing is we're going to be utilizing redis as our database our cache provider and within the address we're going to be storing and caching the data there and once we actually store the data in redis we're going to be seeing how we can actually reutilize the data inside the fradis instead of actually going every time to the database and get the information so this video will be basically will be able to help you to see how we can actually Implement caching inside your.net6 a web API applications you can see how you can set expiry time to the data how you can actually install alternative information from your cache as well you're able to see how you can actually utilize this within the docker containers great so now that we have covered all of the that the next step for us is basically we're going to be creating our web application so let's go to our terminal let's make the subject bigger perfect so once we are in our terminal what I'm going to be doing is I'm going to be navigating to my desktop work let's say learning I'm gonna put dotnet so I'm gonna say caching and then I'm gonna create a new applique web application and here as we all know to create a web application we're just going to be utilizing the.net new keyword so we're going to put dotnet new web API and I'm gonna call this a let's say call it caching uh web API something like that and now it's going to create the API for me perfect now that has created the web API for me what I'm going to do is I'm gonna go to the caching folder and I'm just going to open in Visual Studio code okay perfect now let me just fix those sizes directly uh let's make it 32 32 and let's zoom in a bit uh okay let's see if this is looks good yes I think maybe a bit smaller that should be fine okay that should be fine or we can make this a bit bigger and just make this zoom level sorry to make this 30 instead that should be fine as well okay so once we have done all of that let's say not now the first thing that I want to do here is basically just open a terminal and inside my terminal here all I'm gonna be doing is just put dot nut build I just want to make sure that my application is building as it should be and as you can see here I have built succeeded which basically exactly the information that I want so once we have done that the next step is because basically uh we're going to be utilizing at others under this is going to be our main a cash provider but before we jump into that there is one point that I would like to clarify is caching is already there's two types of caching that actually exists and let's take a look at this before we actually jump into more of this so caching is there's two level so there's gonna be the in memory cache oops I don't know what happened let's zoom out I think that's weird I'm not sure why it zoomed out like that but that's for later uh let's go down yes we have the M memory cache and we have the other one which is going to be the distributed cache because it's really important for us to understand the difference between them because if you if you come across you understand the difference so what's the difference between these two okay let's make it like this so the main difference between the in memory cash and the distributed cache is basically the N memory cash lives within the application itself so let's say we have a server and this server is compromised of let's say five gigabytes of RAM it has two CPUs and one terabyte of SSD for example and this is the server that we're running on so let's say if we have an in-memory cast what's what would that will do basically a chunk of the ram that we currently have it's going to be utilized for caching the information so let's say right now our our server has five gigabits of ram so instead of having five for example we're gonna have one ram dedicated for the cache and the rest is going to be interesting for the application so the first thing that we're doing here is we're actually reducing the capability of our application because we are reducing the available memory for it so from private one to four but on the other hand what we have here is we also have the cache available for us for 1GB and that cache will basically it's gonna be much more faster for us to access information from within our Ram than actually try to access it from a different service so right now as we said inside our Ram is going to be separated to memory for our application and basically memory for the cache and that way because it's inside it's called because it's stored inside the memory is called a in memory cache and that's really important because as we said it's fast but it's taking resource from our application on the other hand there is distributed cache like redis which we're going to be utilizing in this session and basically redis is like a completely separate application which which runs alongside of our web application or web API and it's responsible for storing a die cache there so what's the benefit of having register and other than in memory basically redis is a much more distributed one so what does that mean so let's first of all it will not take any resource from our application and that's really important to understand because if our application is really high performance we need every single bit of resources that's available for us to actually achieve that level of performance that's needed so that's the first point the second point is because our redis lives outside the actual application it means that once our application scales up we will be actually able to utilize that cache with all of the different instances that we have scaling up so for example let's say my application is running on one server right now and it's actually running as it should be but what happened for example after like let's say there's a big big users in my application and basically my application users goes from 100 users to let's say 50 000 users so what's going to happen there the application and the service is going to scale up so from one server I could have for example 20 or 25 servers available for me and basically if I have a distributed cache all of these servers will be able to actually communicate with that cache directly and with with the radius cache directly and put the information from there instead of every single one of them have to respect to manage their in-memory cache but at the server will be able to actually provide this information for me so this is really important for us to understand so let's do a quick overview of what does this look like so let's say here this is my application and I have for example the ram so this is the ram inside my application and basically this drum is going to be separated into two let's make it like this for example Center back and this one will be something like that so this is in memory so basically we're gonna have 1GB for example as we said for caching and the rest for example this is all hypothetical so for the last four is going to be for the application and here we can see that for example and this is out of the 5db that exists for drum for example and here we can see that how it's different and let's say the application will scale up so this will be duplicated on all different servers so we can see here that it's going to be duplicated duplicated so on so forth and here basically we're able to see it at the level of complexity of managing the RAM and basically the performance head that we might get on the other hand let's say this is our application let's take it again so this is our nice application here our web API well then I'll just call it up and basically instead of this app relying on storing or basically managing its own memory what we can do is we just you can utilize Radice and basically Radice will live alongside the application and we're going to be able to connect to it so let's say this scales up all we need to do is just connect these instances from here into radus and basically all of them now are sharing the actual memory that exists and here we can see the main difference first of all not no Performance Set is being occurring on our application second of all if scalability is already available for us out of the box because we're utilizing the same address instance and on top of all of that all of the performance of redis it's the basically whenever the requirements gets higher or for example we need more access to cash or this will actually manage this for us instead of us having to manually do it so I just wanted to point out here the difference between in-memory and distributed one because basically we're going to build nothing that distributed one inside the example that we're going to be seeing today so one step we have covered this point the next point is how are we going to be running around this inside our machine right now because there are this it's a very powerful tool and it's available for us what you need to do is you need to have Docker available so if we go to docker what you need to do is you need to download Docker for your own machine it's a concise since I'm on Mac I need to download the Mac version if you're a Windows or Linux you can actually download it it's for free for personal use so it's really good you don't really have to pay any money for it's completely free so once you download it and install should be able to see like a small whale icon here on top and basically once you open it you will you will be able to see something like this so like a dashboard with a green icon here green whale and this green will illustrate that the application is running successfully so once that is done the next step for you for us is what we need to do is we need to go to our terminal again and basically what we need to do is we need to run some commands inside our terminal to run redis so because uh I have a different video that goes through containers how we can run them and all of that I'm going to be linking it here somewhere if you want to learn more about that but if you're interested in this please put a comment down below and I'll explore this in much more detail in a future video but for now we're just going to see the command that we need in order for us to make red is available for us out of the box so how what are we going to be doing basically what we need to do is we need to run this command Docker which is basically what referring to the docker instance that we want to utilize and then I'm saying that it needs to run something I'm giving it a name and this name is going to be for example Myra this we can call it whatever you want here make sure there's no spaces within the name and then I'm gonna specify the port that it needs to run on and basically the default teleport is 6379 so I'm going to be utilizing the same one and basically once that is done I'm just basically telling you that this needs to run in the touch mode it means that it will run without actually missing the console log of others I just wanted to run and run in the background I don't want to see it and once that is done I will I wanna I wanna tell it which Ms I want to use and I want to use the redis image if you're wondering how did I know that basically whenever you go to Docker there's a a search icon here I just want to put redis and where is it they changed this website all the time let's see through this Docker image okay so we need to have the docker.com to find that my mistake and basically we can see that this is the this instance that we have and basically we can see here say it are some of the commands so basically what I did is I came here to Locker Hub I checked the official images that exist I search for radius and once I searched for that this I will be able to click on it see the different ways that I want to implement that we can see here we have different examples of how you want to run it so on so forth and basically what I did is I run this command so once you run this command I have already run it so I don't want to run it again but once you click on enter you basically the application will run and the way under this basically will run and how do we do do you verify that this is running all you need to do is basically type Docker PS and once you type Docker PS you can see here that I have basically red is running it has been running for two days now on my machine and we can see it's being connected to the port 6379 over TCP let me zoom in a bit so it will look cleaner yeah so you can see here that my Radice is already running and basically it has the name Myra this that I have already provided provided for it and that's all I need to do in order for me to have read this so as we can see here from a single line encore inside my terminal with the utilization of a Docker I was able to have a full instance of address available on my machine and running directly I didn't really need to go out of coffee I can't do it but I didn't really need to do a lot of configuration installation version management Docker took care of all of that and basically all I needed to do is just just run a single line of command and it's running for me perfect so once I have done all of that the next step is I want to go to my code here and I'm gonna start building my application so first things first is because we're building actually a web API and I want to connect to the database so we can mimic the live traffic what I'm going to be doing is I'm going to be utilizing postgresdb in order for me to be actually uh to actually connect to a database so that's going to be my first task is basically connect to post class installed at all the different packages creating an application DB context a very simple one one single table and then we're gonna see how we can actually implement this as a server caching as a service within our.net6 API so once I have done all of that the next step is for me I just want to put dotnet I'm gonna start installing my packages so it's going to be.net add package see if it's looking good on the screen yes it is it might it might turn it down but that should be fine then I'm gonna put Microsoft Dot entity oops okay let's clear this out so it will appear better on the screen or we can zoom out of it okay I think that should be fine and let's clear this okay so it's going to be dot not add package Microsoft dot entity framework perfect so now that my nuget package has installed successfully so let's do it again let's see if we can see it put it up up okay you can see that not add package Microsoft Entity framework core so that's gonna be the first one the second one is going to be dot not add package npg SQL dot Entity Framework let's clear this up so it will be easier for you to see so clear let's do it again so it's going to be.net add package uh and P G SQL Dot entity framework core Dot postgres SQL and let's run this we can see it has installed successfully let's clear this again and the third one is going to be dot not add package it's going to be entity Microsoft excuse me dot Entity Framework core dot design great now once we have done that now we need to install the tools so that not add package Microsoft dot entity framework core dot tools great then right now I need to install Reddit so basically it's going to be not across clear this so it's going to be a DOT not add package stack exchange exchange and now that it has been installed successfully let's install the last one which is going to be.net dot add package Microsoft dot extensions dot caching dot stack Exchange redis perfect so now that we have installed all of our packages the next step is what we need to do is we need to go to our CS approach and make sure all of the packages are there so right now if we go to caching web API and we can see here that I have all of my all of my packages installed Entity framework Core Design tool stack and change the Traders post across rathers and basically swashbuckle for the uh for our interaction with our web API so once we have done all of that the next step is we're gonna start creating our model and basically uh we're going to be utilizing as we said postgres so I have different video to see how we can actually install and set up postgres on our machine I'm not gonna go through this right now I'll link that video here somewhere where you'll be actually able to go through that process but just for the sake of this uh information uh we're gonna assume that posting has already installed and configured and we're going to be utilizing that configuration in order for us to actually connect to our local database instance so first things first inside the root folder here I'm gonna be creating a new folder I'm going to call it models and inside this models I'm going to be creating a new class and this class I'm going to call the driver basically we're gonna building a F1 application I think if you watch my videos you can tell that I'm a big F1 fan and basically everything revolves around F1 when it comes to testing applications so driver and let's make this.net6 look and feel and we're gonna have a very simple driver tables is going to prop and ID and then we're gonna have prop string name and we're just going to put the driver number and that's it prop and oops crop and driver number very simple and once we have done all of that and basically now we have our models ready the next stuff first is we need to start actually building our app DB context so again I'm going to create a new folder and this folder we're just going to call the data and basically within this data here I'm going to be creating a new class and this class I'm going to call it up DBA context and let's make a.net6 compatible or basically just look and feel all I'm going to be doing is I'm going to basically and hide it from the DB context class it's gonna tell me I don't know it so let's add using and then basically I'm gonna build my Constructor and it's going to be very simple to be context options DB context and I'm going to pass the options and then all we need to do is pass it back to the base so it will know how to utilize it and lastly I'm gonna add my driver table so that should be very simple all I need to do is public so dbsat basically I'm telling it that it needs to create a table and it's gonna be the driver table oops it's going to be called the drivers and that's it at night now if I click on this one here perfect so now I have my application DB context available for me great so once that is done next step is I'm gonna go to my connection string and I'm gonna basically connect it to my local instance of postgres so let's add here conduction strings and I'm gonna call the sample DB connection and I'm gonna just copy paste this conduction string because I already have it instead of me try to type it again again this video is not really how to set up uh postgres there's a way different video if you want to really learn about postgres and how we can actually implement it there's a way more in-depth video of how we can set up postgres connected to your database I'll link it here somewhere in the description down below so it will be available for you directly to you to learn more about it but for now we're just assuming that everything is already set up so once that is done so once that is done the next step is I need to go to my program.cs and let's make this a bit smaller and just make sure this is looking good okay inside my Builder here all I need to do is just basically add my connection to my database so it's going to be Builder dot Services dot add entity framework npg SQL that's correct I'm gonna say that let's put it on the new line dot add context contacts at DB context DB contacts here and then I'm gonna pass the app DB context see if it's going to require us let's add this and once that is done all I need to do is now fill the options and basically it's going to be responded here yeah okay this looks good so it's gonna be options dot use uh and where is it use npg SQL so this scanning is going to require another using yes exactly and then once that is there I need to just pass like on Maxine string so it's going to be a configuration actually builder.configuration .configuration.getconnectionstrings oops not children conduction string and then all I need to do is just pass the conduction string name that I have so all I'm gonna do is go to settings not settings this one to op settings copy this one put it here and now basically I should be have direct access to my application perfect once that is all done what I'm gonna be doing right now I'm just going to implement a migration to make sure that the table is there and basically my application is running as it should be the database is there the app to be contact is running that's all we need to do so let's clear this again and let's make this a bit bigger so because we're running Entity framework core uh we're just going to be utilizing.net EF migrations uh that I'm just going to call it initial migration and right now this should basically create a migration except for us and we should be able to see that there's a new folder cleared migration created as we can see here and basically we can see that inside this we can see that we are able to create the folder with all of the columns sorry you create the table with all of the columns that we need so once we have created all of this the next step is of first of all we basically create the migration the next step is we need to implement the migration of our database so now it's time to implement this migration so to do that it's going to be.net EF database update very simple as we can see the migration has been updated successfully so right now if we open DB beaver and if I just refresh here you'll be able to see that I have a driver's table now and it's going to be if you click review table it's going to be empty and has ID name and driver number and the data is empty exactly what we wanted so once we have done all of that the next step for us is we need to start creating our caching service and this caching server that we're going to be creating is we're going to be utilizing our dependency instructions so we're going to be creating as a service we're going to create an interface and then we're going to be creating an implementation for that interface we're going to connect it to our problem.cs and then we can actually inject it in any controller that we want so inside the root directory of our application let's create a new folder we'll call this folder services and inside the services I'm going to create a new interface and I'm going to call it icash service let's make this stop not six look and feel perfect so now we're gonna have three basically a method inside our interface the first one is going to be t get data of type t and we're gonna pass the string key we're going to explain why did I make it like that and then we're gonna put bull set data of type T again and it's going to take a string of gonna be the key then it's gonna take the T which is going to be the value that we want to store and then we're gonna take the date time offset I'm just going to call this expiration time expiration time and lastly we're gonna put object because basically we're going to be removing data so remove data and just gonna take the key so this interface here has three main methods so the first one is going to be get data then it's going to be the setting of the data and then removing of the data and the reason we made it as a t because basically this is going to be like an anonymous type because we don't really let's say we have a list of derivatives we have a list of teams we have a list of equipments we're going to have in a normal database you can have like I don't know tons of tables like maybe 20 30 40 50 100 table there you don't really want to create a service which basically very hard-coded to those tables you want to make it as generic as possible and basically when we do it like in this way you'll be able to pass the type of file that you want to extract much more easier so it could be a single a single record it could be a list of a hundred records it could be anything that we want so that's why it's really important for us to basically make it as genetic as possible so we can actually re-utilize and that falls within the solid principle so write a irrigated ones and use it rather than we creating multiple times so once we have created the actual uh interface the next step is going to be the actual implementation for this so we're going to create a class we're going to call it cache service and let's remove this perfect and now that we have done that let's do the implementation let's move this a bit back the first thing that we need to do is we need to implement the interface so I cache surface it's going to say oh we haven't implemented okay we'll implement it now and then what I'm going to be doing is I'm going to have an i database and I'm going to call it cache TB and let's fix this references and what I'm going to be doing is I'm going to create a Constructor [Music] and I'm just gonna call this create a variable called redis so I can connect to the actual instance of redis and I'm going to put connection multiplexer connection ability flexor I think that's how you spell it let's see yes okay connection multiplexer dot connect and basically what I need to provide here is the actual path or basically the actual endpoint of my Radice so if you remember if we go back to to our terminal and let me zoom and again you'll be able to see that my redness instance is running on 6379 on localhost so that's what the instant that needs to be so it needs to be a local host on that Port so basically my application will actually know where my latest instance live so in order for me to do that or I'm gonna put this localhost with the port 6379 so just like a disclaimer here this is not the best way to inject the configuration for your rather server inside our service again this is a sample application I did this just to make sure that I would able to do it quickly the best way to do it is to store it inside the configuration and pass it along to the service right now this is just like a quick way so we can actually demonstrate its capability but again this is not the best way to store this inside your service just an FYI here okay so once we have done that the next step is we need to actually initialize the cache so we're gonna put cache DB equal right this dot get database and basically right now we're able to connect to the database and something I forgot to do we need to make this as a private so now we have private database why it's not happy okay we referenced the wrong one so let's remove this one and yeah that should be fine and now we have our redis connection ready so now when you start need to implement these three methods so the first one is going to be the get data so let's remove this and basically what we're going to be doing is we need to check first of all we need to connect to that instance get the value if it is there we return it else will return an empty object so that's what we're gonna be doing so we're gonna put VAR value out of our value that should be fine equal underscore cashdb dot cut actually string got and basically string that here all we need to do is pass the key and it will match the key to whatever exists inside our redis cache because basically something maybe I forgot to mention radish is basically a key value so key and a value key and a value so for example if I call it users it's going to get me a list of users if I call it drivers the sub drivers driver one is going to get me one driver something like that so it's a key value pair so I need to refer to the key that I want to get inside the formulas so this is going to be the key then I'm going to check if not empty so basically string dot is is null or white space is not what I'm telling us say of value so if it's not I'm gonna return the value let's return it okay that's another point I want to mention so right now what we're doing is let's say we have a list of drivers that have 100 driver for example and this the way it's being stored in redis is like being stored as we said key value and it's being stored as a string the one the way we want to process it is we don't want to really process a string what we need to do is we need to convert it to an object and here what we need to do is we need to serialize it and basically what that means is we're going to be basically converting it from a list of string to an object that we can actually utilize with in our C sharp code and this is really important so right now what we're going to be doing is just we're going to take this a list for example of objects that we're gonna we're gonna have we're gonna make sure that the string is not empty because if it's empty or or not we're not going to be able to serialize it once we make sure it's not empty or not and we are able to serialize it we're going to be serializing it to the type of object that the user has passed and then we're gonna return it so we're gonna put return uh return it's going to be Json serializer Dot deserialized I'm gonna fix this first needs to realize type D and then we're gonna take the value and that's going to be basically it the sun here was saying possible no reference that's fine what I did this check here else what we're going to be doing is return default and default means here if we hover over it it says basically as we're returning a nullable type of that object that we needed so basically already covered so that's going to be the good data the remove data is also going to be very simple whereas all we need to do is let's go here and we're going to do the same thing so far exist we're gonna say so first we're gonna check if the key exists or not before we remove anything so we're gonna put cache DB dot key exists just like I said a built-in functionality and we're gonna pass the key so we're gonna say if exist what we're going to be doing is return which is going to return a Boolean cache DB dot key delete basically we're deleting the data from there and we're gonna pass the key else what we're gonna be doing is return false very simple so we checked first if the key exists if the key exists is basically done we initiated the key delete functionality if not we just return Force very simple straight to the point so once we have done that the next step and the last one here is going to be set data and sad data is quite simple as well everything here is quite simple so we're gonna put the file expiry time so we need to get the expiry time off actually when we are setting this data equal expiration time which is going to be getting from here dot date time dot subtract date time dot now so basically we're gonna be passing uh passing along when it's going to be the expiry time five minutes 10 minutes two minutes one minute whatever we want from here and once we exp once we pass it all we need to do is check whatever time we are in and then we're gonna subtract it so once that is done all we need to do right now is VAR uh sat we're gonna say it actually put this set equal underscore cache DB dot strings that and here it's going to ask us we can see for the key first so we're gonna put the key then what we need to do is we need to convert any object that we got into a string because that's really important we cannot store it as object we install them as strings once we store them as strings and then we pass the expiry time so in order for us to basically do the uh do the convert them to a string what we need to do is we need to serialize them so in order for us to do that we're gonna put Json serializer or serialize and we're just going to serialize the value and lastly we're gonna just pass the expiry time and I think that's it yeah and then once that is done all we need to do return if it's successfully or not yeah let's make a dollar just drag this even better okay so now that we have set up our service and basically we are able to uh configure it the way we want we basically were able to create an interface Implement that eight interface connect our discussion now we need what we need to do is we need to update our program.cs in order for it to be first aware of this interface then we're going to be creating our controller where we can actually able to see and implement this uh service inside our controller so let's go to program.cs and I'm gonna do it after the connection string All I'm gonna say is Builder dot Services oops oops dot services that add sculpt and basically here I'm gonna pass the I cache service and the cache service just gonna close it oops close it like this and let's fix this perfect now let's just do a DOT not build make sure everything is building as it should be foreign excuse me so it built successfully and we can see that we have built succeeded which is exactly what we want so once we have done all of that now let's create our nice controller so where is our controllers folder let's create a new class and this class we're gonna call it drivers controller typical Visual Studio code so we're gonna put drivers controller.cs I'm gonna take whatever exists here similar all of this we just updated instead of me rewriting everything just paste this here and we're just gonna call this driver's controller and the space to see here and I think that's it and we don't really need this so let's remove this well we need this there will not really need this so now we have a very simplistic control controller all we have is a Constructor in it great so once we have done that the next step is we need to actually inject our services and our application DB contacts so here we're gonna put private read only logger and we're gonna put a Salient our logger apologies we're gonna put I cash service I'm going to call it cash service and it's gonna ask me to fix those references so let's fix them now and let me copy this and let's put this on the new line and all we need to do is just see here do it like this just remove the underscore okay it looks good and we're gonna put here underscore cash service equal cash service we're just injecting a new uh interface inside our controller I want to see this again but not right now for our FDB context so it's gonna be a private read only space app DB context I'm gonna call it context and let's fix those references let's copy this one again let's put it here let's remove this and this is basically going to be underscore context equal context perfect so now what we did is we have injected basically the caching service and our application application DB conduct so we can utilize it another way is you can have for example like the unit of work implementation where basically you just call you run the fork here again for simplicity's sake I'm directly injecting my DB contacts this is not should be like the way you should actually build uh inject your DB contacts into your controller but again this is all for uh this sample application to see how we can actually utilize cache so once we have done all of that right now let's start actually building our uh endpoints so the first endpoint that we're going to be taking a look at is our get endpoint for all of the users so we're gonna put first HTTP get and we're gonna say drivers because we're going to get all of the drivers list and I'm gonna put public async task I action result and we're just going to call it gut very simple and the first thing that we're going to be doing here before we jump into this there's a nice diagram that I want to show so let's go back here and let's go to I think here on up I can't really remember where it is let's see let's zoom out a bit so we can see it on 100 okay this is it so let's check this out 150 okay so basically here this is what we're gonna this is the logic that we're gonna be implementing and this logic is basically gonna be through with us through all of the different uh uh to all of the different requests that we're going to be doing so in essence first things first we're going to receive a request once this once this request is being received the first thing that we're going to be doing is we need to check our cash do we do we have an answer for this request inside our cache yes or no if if yes we're gonna go check the cash information so inside our cache does this information that exists within our cache has expired or still valid if it's still valid we can take this information from the cache and return it back to the user else for if the cache is not there or if it has expired what we need to do is we need to go back to the database get the information from there then we need to actually set the cache and then we return back to the user so we can see that we have this flow of uh first checking the cache and then basically whatever data we get from the database we need to set back in the cache and then we can return the data and this is the model that we're going to be following now so if we go back to our Visual Studio code the first thing as we said we need to check the information from the cache check cash data so here we're gonna put VAR cash data equal underscore cash service Dot get data and here what do we want we need to get an i enumerable of a driver basically a list of drivers and basically and I want to refer to them from the key drivers that's it let me fix those references so basically here I'm just telling it needs to connect to the cache service it needs to get the data I'm passing the anonymous type which is here going to be a list of drivers and I'm giving it the key which is going to be drivers and first of all we need to check if cache data is not equal to null or and sorry we can say cache data dot count is bigger than zero what we can do we can return cache data we can return OK the 200 request 200 response with the cache data as simple as that all we're doing is basically checking checking our cache that this information exists our cash yes or no so in case FTS we need to make sure it's not noddled we need to make sure it's not an empty string based on that what we're doing is we're serializing and returning everything back to the user so the next step is if it fails so we need to get from the database so first of all let's get it so it's going to be let's say cache data equal await underscore dbcon oops context dot drivers Dot uh let's say to list async as simple as that we're getting all of the drivers list that doesn't really matter so once we have gotten all of this list now we need to actually say if we go back to the diagram we need to make sure that we are setting the cache so now we need to set the expiry time so for this we're gonna put four expiry time equal date time offset dot now dot add for now it's going to be five minutes so we're gonna say add minutes oops I'm just gonna make it five minutes actually for the sake of this let's just make it 30 seconds at seconds let's make it as the 30 seconds okay just for the Simplicity sake of this sample okay so now once we have done that all we need to do is go back to the cache service we're going to put set data and it's gonna be again as an i enumerable of driver and then from there we just need to pass the key which is going to be drivers and then what we need to do we need to pass the cache data which is going to be the results that we want to store and lastly the date time offset is going to be the expiry time and that's it and once we have done that basically we just return okay with the cache data so this is a very simple implementation how we can actually get the data we checked first if it exists or not if it did we sent it back if then we got from the database we started in the cache and then we basically returned it very simple straight to the point so another one is basically let's see how we can add the data so now let's see how we can actually set the data so we're gonna put a HTTP post and we're gonna say call it add drivers and this is gonna be public as you think task I action result and we're just gonna call it post and we're gonna put driver we're gonna put value and here basically what we need to do is we're just going to add it through our DB context and basically let's see how we can do that we're going to save forward added objects equal await underscore contacts.drivers.ed oops add dot add async and we're going to add the value and from here all I'm going to be doing is I'm gonna put VAR actually it's gonna be something around the we need to set this in the cache so we're gonna put cash service Dot set data it's going to be a driver and basically we're just going to call it driver very simple and actually we need to remove the data in case there's another cache with the same driver uh okay uh whatever we can do it in a way I can do it in this way so let's put the added object value dot entity and let's take the same expiry time let's copy paste it here and we put here expiry time something like that and here what I'm gonna do is just gonna append the ID so it will be cast for this ID something like that value dot ID yeah that's that's a better way to do it and then what I can do is just put a weight context dot save changes async and first return okay just return edit object dot entity okay so now we have seen how we can add and how we can extract the last one that we're going to be doing is we're going to be seeing how we can actually delete stuff from our cache so for this we're just gonna put let's see it's going to be delete so let's make it HTTP context I still actually HTTP delete it delete the driver and it's gonna be public public async task I action result and basically we're going to call it delete all we need is the ID and ID so first of all we need to check if it exists or not uh when so we need to get from the database so far exist we're gonna say it equal context dot drivers but first or default async and we're gonna just make a match x dot ID equal equal ID and let's make this available first or default async just make it and now we're gonna say if actually yeah if exists not equal to null as we just return uh we just returned not found because basically I don't want to give a lot of information about it so I'm just going to not found or yeah not found that should be fine again it's all for the demo and here what I can do is very simple put context dot remove exist and then I can put caching service dot remove data and it was driver what did we do it like that okay let's copy this driver.id so without this this and this and that should be it and lastly once we've done all of that we're just gonna put contact actually await contacts to save the changes async okay great and lastly once you delete the return no contact so return no content perfect so this is gonna be our application very simply we created three actions the first one is to add sorry the first one to get everything the second one is to add and the third one to delete here we are covering the three main functionalities of our cache service so once we have done all of that the now is now time to test it out so let's see so inside our terminal let's clear it out we're going to put.net build yeah to make sure it's building foreign perfect now if you go to this URL actually before I do that let's meet the disable https it's going to create an issues okay let's try it again so let's copy this one here and let's actually open it in the same web browser and let's take it from here and let's put Swagger forward slash index.html and we can see from here that we are actually able to see our three endpoint so let's try to add a driver now and then add the first one id1 uh we're gonna put uh we're gonna put sir Lewis Hamilton driver number is 44. so now I'm gonna just execute and we successfully added right now if I get it try it out execute I was able to get it directly so I've execute again we can see how fast the response is we can see that I'm able to directly get the results but after 30 seconds this will then take a bit longer because it's gonna start getting from that database so let's see let's wait 30 seconds I think 30 seconds should have been passed now uh I think if we open it in insomnia and so let's open it insomnia we're able to see the time frame so let's just put this thing here and let's zoom in okay I think this should looks good let's see okay so what we're doing here is we're just going to create a new request and let's copy this URL and let's paste it here so right now we can see that this took 48 milliseconds what I'm gonna be doing is I'm gonna be creating a new driver so let me take this request another new requests and makes make it post and I'm just gonna take the same body and put body as Json paste it here ID equal to and this is going to be myself driver number I don't know 11144 let's see send is being added so now if I get this we can see that my response time is way lower so we can see here it's getting 29 20 because it's cutting it from the cache this is all and then went back to 24 then it cached it so right now it's 30 30 28 20 39 because it went to the database after 30 seconds and then it catch it again again because it's local on my machine it's not gonna really show a book of a difference within the time but actually when you run it on a live production environment and you have connections between different database server you're going to be able to see all of these differences lastly what let's see let's try the delete so now we have done all of that now let's see the deleted driver so I'm just gonna delete idea number one execute we can see it has been deleted successfully we got the 204 uh no content has been found which means that all of our applications running as it should be the data is being stored in redis and basically we're able to pull it out with the right correct expiry date so now let's do a quick summary so in today's session we have explored why do we need to use cache and how it's affect our uh implementation how how it affect the performance of our API we saw how we utilize Stratus install it on our machine uter by using Radice we saw how we can actually able to add this to our web api.net6 web API we'll be able to see how we can create all of this service or caching service we can see how we saw how we can actually integrate it within our controller and basically we're able to see how we can implement it to four different functionality like adding removing and extracting so I hope this video really helped if you like this video please like share and subscribe it will really help the channel as well if you'd like to support me please consider supporting me on patreon as well on or buying me a coffee if you support me on patreon you'll be able to get access to all of this source code I hope this video was helpful and have a great day
Info
Channel: Mohamad Lawand
Views: 4,526
Rating: undefined out of 5
Keywords: .net 6, .net, api, step by step, c#, dependency injection, coding, entity framework c#, entity framework, asp.net core tutorial, api security, json api, .net core, asp.net core, web api, .net 6 logs, postgresql, postgres, postgresql dotnet core, postgresql dotnet, redis cache asp.net mvc, redis cache manager, dotnet core tutorial, dotnet core web api, redis, dotnet core, dotnet performance, data caching in asp.net, api caching, api caching best practices, web api caching c#
Id: 6HZVu3kGOrg
Channel Id: undefined
Length: 64min 22sec (3862 seconds)
Published: Tue Oct 04 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.