Redis Caching in Node.js

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] this video is sponsored by dev Mountain if you're interested in learning web development iOS or UX design dev Mountain is a 12-week design and development boot camp intended to get you a full-time position in the industry to learn more visit dev mountain comm or click the link in the description below hey what's going on guys so in this video I want to show you how to implement cash with Redis in nodejs so Redis can be used as a cash mechanism as we're gonna use it here it can also be used as a persistent database like a no SQL type database and I do have a crash course on Redis it's about two years old but it's still very relevant I don't think any syntax or anything like that has changed so if you want to check that out I'll put the link in the description but the advantage to using Redis is that if we're to make a request so we're gonna actually make a request to the github API to get the number of repos for a user and what we're gonna do is store that number in our Redis cache so Redis is basically key value pairs and what it does is it'll allow us to make less requests so it'll cache the data so we don't have to keep making requests and it will speed up our application now we're not going to really build a you know a real application I'm just gonna show you how to implement it but you're gonna see the benefits of it and you're gonna learn the foundations to to use this in your apps and your nodejs apps and of course you can use Redis with other technologies as well now you do have to install it on your system so I'm gonna show you how to install it on Mac and Windows well at least I'm going to tell you how to do it on Windows and on Linux you would use your package manager so aptitude or whatever it is whatever district you're using so you would do that in deployment as far as Windows goes you need to go to this this link here which I'll remember I'll put in the description and you just download the zip file and the zip file has a executable called Redis server and you just want to run that and that will run it on your machine and then you also have Redis CLI which is the command line interface and you can actually interact with you know with your Redis store if you're on Mac I would suggest using homebrew okay so if you don't have homebrew install just go to brew dot SH grab this right here and throw that in your terminal and run it and you should be all set okay once you do that you can run brew install Redis I already have it installed so it didn't probably just tell me that but once you do that it'll ask if you want to basically run it in the background as a service or or not I would suggest doing that that way it's just running and then once you have installed you can actually run Redis - CLI and it will bring you into the the command-line interface and you can see it's running on port six three seven nine so that's the default port and we can actually set values here if we want so just simple key value pairs like we'll set name to Brad and if we want to get that value we can say get name and it gives me Brad so very simple and again you can use this as a database or as you know as cache like we're doing so I'm just going to exit out of here for now and now we're gonna jump into visual studio code and get started with with Redis and node so let's first of all run NPM and knit - why we'll just create a quick package dot jason here and we're gonna install a couple dependencies so npm install Express and we're also gonna be again making a request to the github API so I'm going to use node fetch for that if you want to use something like request or another package you can do so and then we also need Redis which is the driver that allows us to to use Redis within node alright and then I'm just going to install node Mon as a dev dependency so upper case - upper case D node Mon and then we'll just go ahead and add a start script that will run our main file with no daman so let's just say start and I'll have this run node Mon and we'll call it index J s so let's create a file called index dot JSP is bring everything in let's bring in Express and let's also bring in node fetch fetch and then we also want Redis okay and then I'm just going to create a variable for our port I'm going to use environment variable here so process dot E and V dot port or 5,000 if that doesn't exist and then let's also add the Redis port I'm just what I do rid of this and the Redis ports is 6 3 7 9 and it'll change the name of this variable here to Redis underscore port okay and then what we need to do is create our Redis client so we set this to Redis dot create client and then we just pass in the port all right and we need to initialize Express of course so I've set that to express and let's do app dot listen and let's listen on 5000 and we're just going to set this to backticks instead of quotes and we'll put our port number in here alright so we'll save that that should at least run the server if we do npm start ok app listening on 5000 so now what i want to do is create a function that we're going to run when we hit a specific route let's actually create the route for us so we'll say app dot yet and i want to be able to go to slash repos / and then whatever the username we want to get the number of repos for and then when that's hit we're going to run a function called get repos or I mean we're not getting the actual repos or getting the number of them but that's fine we'll just leave that all right so get repos so let's create that function so this is going to make requests to github for data so function get repos and this is gonna take in the request response next okay because this is middleware and we're gonna make a we're gonna use a sink of wait when we make our request so we want to mark this as asynchronous and then and since we're doing that let's use a try-catch in case we get any errors okay so if we get any errors will just do a console error and then we'll do a response with the status of 500 which is just a server error okay so in here let's do a console log and I want a console log fetching data so that we can see when this is actually running and when the request is actually being made and then we need to get this username right here that's passed in which is going to be in request dot params dot username and I'm actually going to just use destructuring here to pull that out so I'll say pull pull username out of request dot params okay now we want to make the request so let's create a variable for the response we want to wait fetch because this is asynchronous and the URL is going to be the github API which is API dot github.com and we want to do slash users slash and then the username okay and that's going to give us a whole bunch of data so we want this to be in JSON format so let's call this data and we want to set this to a wait because is asynchronous and then the response dot Aysen okay just like the front end fetch API if you've never used node fetch and then for now let's just rezzed send data I'll just see what we get so we're not implementing cache or anything just yet but let's try this out so we'll go to our browser and go to let's see HTTP local hosts local host 5,000 and we want to go slash repos slash and I'm going to put my username in here okay so this it gives me a bunch of data and what I'm looking at here is the not the fall public repos which is 174 okay so what I want to do is have the response just say you know the username has 174 repos and this is that this is what I want to put in our Redis cache okay so back in vs code let's go right under where we got the data and let's say con story pose and let's pull that from data dot public underscore repos which will give us that number all right and then this is where we actually want to set to Redis okay our set yeah set data to Redis and the way that we do that is we use our client that we initialized above and we can do dot set now I'm gonna use set X which is it's like set but you can set an expiration because you you don't you probably want to set an expiration because the data on the server could change so I'm gonna set this basically it takes in three three things it's going to take in the key which I'm going to use just the username okay so the key is gonna be the username in this case you know Brad Travis E whatever I put in the URL and then second is the expiration I'm gonna do an hour so 3,600 seconds and then next is the data that we want which is going to be the repos the number of repos okay so that should set it to our red cash and then as far as a response I'm gonna create a function called set response and that's gonna take in the username and it's gonna take in the repos okay so let's create that set response up here I'll say function set response and this is going to take in username and repose okay so I'm just going to go ahead and return a template literal and we'll put some HTML and yeah we'll just do an h2 and let's put the username I'll say username has and then repos github repos okay and that's it that's all I want for the response and let's try that out so we'll save this now we're not implementing the cache just yet but it should save the value to Redis okay with this line right here so let's go back and reload and we get Brad Travis he has 174 github repos and if we go into our Redis CLI I should be able to just say get and then the key which is the username and then we go 174 now if I open up my chrome tools here and we go to the network tab and we reload you can see that for finish we have above a 170 milliseconds if I reload hard 6157 and every time I reload you can see down here we're making that request we're fetching the data so I want to now create a piece of middleware to cache the the value and to use that cash so let's go right above the route and let's say cache middleware and middleware is just a function that runs in between the request and response cycle so when you hit the route the fund this function will run you know in between when the request is made and then the response is given and we can grab any request params or anything like that we can grab the user name and stuff so let's say function cache and since it's middleware we need to pass in or quest response and next and I'm gonna get the username from the URL so I'm gonna just pull it out of request dot params and then what we want to do is use Redis client and we can use the get method and remember we have right now we have Brad Travis E as key remember these are key value pairs so we want to get get it by the key which is whatever the user name is and then we have a callback as a second parameter which has a possible error and then the data are the value so let's just check for the error and if there is we'll just throw error okay and then we're gonna make sure that data isn't null so I'll say if data is not equal to no then we're gonna res dot send and we're gonna use our set response and pass in the username and then the data that is in the cache else then we're just simply going to call next and we're gonna move on and it will make the actual request all right now in order to use this cache middleware we simply pass it in as a second parameter okay so I'll go ahead and save that and now this should work so if I go back so remember it took 157 milliseconds if I reload eight milliseconds okay and if I keep reloading look one two milliseconds and if we go back to the console notice it did we get no fetching data at our it already got put in the cache okay if we look at for another user so let's see let's look up get if I who's Kyle Simpson which is someone I follow and so the first request is gonna be you know $1.99 or whatever because it is making that initial request to get that data to get the number of repos all right but if I reload now it's going to get the cached version which now gives us one millisecond okay and if I keep reloading and then I look at the console it only fetched it once okay so you can see the benefit here and if I remove that cash middleware and we go back and I reload look at 625 milliseconds 186 133 and if we look in the console it fetched every time okay so you can see the benefit here not only it speeds up our application but it also limits the number of requests a lot of times such as with the github API you have rate limiting and you only have a certain amount of requests you can make so there's a lot of benefits to doing something like this with Redis so I mean that's that's pretty much it and obviously this is a very simple implementation of it but it should give you an idea of how to use it and and hopefully you can optimize your applications with it and if we go into our CLI we should be able to say get getify and 51 okay and if you want to I mean I have a complete crash course on all the commands and stuff but if you want to get rid of everything you could do flush flush all and then if we do get Brad traverse see you can see that nil just it just means that there's nothing in there and but if I go back and we're on that that should cash it and then if I run this again there we go 174 all right so that's it guys hopefully you enjoyed this and got something from it if you did please leave a like and I will see you next time
Info
Channel: Traversy Media
Views: 135,087
Rating: 4.9742765 out of 5
Keywords: node.js redis, node.js cache, redis, redis cache, node redis
Id: oaJq1mQ3dFI
Channel Id: undefined
Length: 17min 41sec (1061 seconds)
Published: Tue Aug 20 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.