How to effectively use Redis Cache in .NET Core (Framework, Standard)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Great stuff.

👍︎︎ 1 👤︎︎ u/newdevin 📅︎︎ Feb 06 2020 🗫︎ replies
Captions
hello everybody my condition I'm gonna show you how you can get started with Reddy's cash in your dotnet application this is valid for dotnet core framework and standard Redis is an open source distributed in memory data structure store used as a database cache and message broker in this video we're gonna cover all three it supports many complex data structures but I'm only gonna focus on strings because that's probably the most common one in the future we're gonna make a more advanced video covering more complex data structures race has built-in replication which we're going to show in this video and it allows us to have a very performant distributed cache for our application and our system it's usually used on top of a database in order to cache data from that database making it more efficient because we don't actually go to database and stress that we just cash it for some amount of time in Redis and then we use Redis as a quick way to access that data this field is part of my doesn't cause here so we don't wanna miss any episodes please subscribing the certification well to get notified when I upload a new episode so as you can see here I have a simple API with a couple of endpoints currently this API has a single controller called cache controller and this controller is used in order to allow me access to a cache now these cache is exposed through the eye cache service interface and this interface is being implemented by the in-memory cache service this service is using an in-memory cache as you can see here that's a dotnet class and then I can do get and the type and I'm getting the string based on the key I'm providing so it's a key/value pasture and then I can also set the value so I can say key and value and I'm setting it here and I'm returning success and if I really quickly run this I'm gonna show you how it looks like in postman so I have my endpoint here and I say cache and then test is the key of the cache entry when I search for and I say send and you can see that it 404 not found because the key doesn't actually exist in the cache but then I can go here in the post endpoint and say key test and value my cache value here and I press send and it says okay which is good and then I can simply do the test get endpoint again and you now see the value because the value now is in the cash so a very basic in memory cache exposed through a controller what I want to do here is I want to change that in memory cache into a read this distributed cache and how do I do that well there's a very helpful package that allows us to access Redis and that is made by the stack overflow cat is under the stock exchange umbrella I can show you exactly where it is right now so you go to the dependencies monitor NuGet packages and you say stack exchange Redis and it's the first one you're gonna see it's a very popular package and I'm gonna go ahead and install it so it is now part of my project and there is a very important interface and class which we need in this class an interface is the AI connection multiplexer now I won't go really in depth on what the connection multiplexer does behind the scenes but imagine it as your entry point to Redis this is what you should be using and this AI connection multiplexer should be registered as a singleton and maintained throughout the lifetime of your application you shouldn't be just reinstating every time so what I'm gonna do here is I'm gonna say services dot add singleton and what I wanna register is the eye connection multiplexer that's coming from Redis and then in the lambda here I wanna say connection multiplexer the class dot connect and here I provide the connection string for my connection I'm gonna use a configuration to get that so I'm gonna say configuration dot get value and then that will be a string and the string with me read this connection and I'm gonna go at the app settings of Jason and I'm gonna add it here and what this would look like where I'm gonna run even darker localhost so I can simply say localhost like that but I'm also going to specify the port because I don't need to because 6 3 7 9 is a default but just for clarity purposes I'm gonna add that here and now what I've done is I registered multiplexer which is my entry point and then what I want is to change this add singleton ICAST service to in-memory cache service to a read this one so what I need to do now is I need to go to services and say add a new class I don't need to delete the previous one or modified dependency injection we'll deal with that for us this is a great thing about dependency injection and then I can say readies cache service and this class will now need to implement the I cache service interface and as you can see it asks us to implement the missing members so I'm gonna go ahead and do that and as you can see they're now implemented and what I need to inject here to work with this is the I connection multiplexer that I just registered so read-only my connection multiplexer and you can see here and then I will use a ride the shortcut to inject it from the constructor and now we have access to Redis now how do I actually write and read stuff from it there's a step that you need to do first before you can actually write or read you need to get the database because Redis has a bunch of databases within it and they can be used for different purposes but you're most likely aren't going to use them so for that reason I'm gonna default it to the one that Redis defaults anyway which is the 0 which is the first one so we're gonna save our DB equals connection multiplexer dot get database and I'm gonna leave it as it is it's going to default to the minus 1 actually and then I am able to use this database to get and set values so in Redis it will look like this DB dot string get and I can accept sink or a sink I'm gonna go with the async here and I'm getting a string back and I'm the key and the key is the key itself and then I just say return a weight and I do a nice thing here and literally that's it you now have access to that string of course if you wanted to have a more complicated data structure you could very much get that string serial from a JSON string to a poco object and return that Pocock this is totally doable using JSON converters but in this example I want to use it and then for the setter I need to do the same thing I need to get the same data base here so I'm gonna copy that here and I can say a weight DB dot string set a Singh and I can simply say key and value and that's it I simply have to change it now to a sink and it all works and keep in mind that Redis works with the set scenario the set approach and set it's also equivalent to absurd so you don't just insert you insert or you update if it's there so you don't care whether it's there or not you just put the value in there and you replace everything existing and that's it so now we have our Redis cache service here we're gonna go to the startup and instead of registering the in-memory car service I'm gonna come at the out just in case we need it in the future and then I'll simply register the Redis cache service and in fact I don't think order matters because that's a lambda in here but let's make it clear and show that you need the multiplexer here and now obviously I need a red is running and I don't have that so I'm gonna run this in docker I'm gonna go in console and what I can say here is docker run and then I'll specify the port because I need to run it locally and I'm gonna say six three seven nine six three seven nine again so that is the external port and the internal port and then I need a name and I'm gonna name it Reddy's master I'm gonna explain why that's master in a second and then there's another configuration where I have to say readies replication mode equals master I don't need to specify that now but I'm gonna show you how you can actually use replication in your Redis cluster if you want and I think that's pretty interesting so I'm gonna set that up now he just adds a few environment verbs another one is allow empty pass or Wow that's being cut off it's not really nice let me make this smaller and then I will say yes and then specify the image I wanna run which is the beat Nami first last readies latest oh you can't actually see it but yeah you can see it now so red is first last like this and I can run this now it says unable to find the image locally because I don't have it in my local cache that's probably what you're gonna see as well and now it's gonna try to download it and run it I'm gonna skip this downloading wait in case it's slow and we're gonna see what happens once it's downloaded so the download is not completely you can see that my Redis service is running so I have here a tool called the Redis Desktop Manager and I'm gonna use that to navigate Redis there's other tools as well you can choose whatever you want if I test the connection it says it's okay so I'm gonna go ahead and connect of course I need to give it a name so I'm gonna say master and press ok and you can see that there are no keys here in the class or these are the databases I was talking about so the minus one is zero if I make that smaller I can now run my application and hopefully assuming I did everything right we should be able to connect to that Redis so back in postman I'm gonna try to get this value again and nothing comes back this is good because nothing is in the cache actually and now if I try to create this value you can say send and it says ok and if I now do check my cache value is here which is awesome and if I go to the navigator and I say refresh you can see that I have a single key with my value of 19 bytes saying my cache value here so for the basic setup scenario of putting a string and getting a string back literally that's all the code you have to write of course if you have serialization you can use the JSON converter to change the string to a Paco object but other than that this is all you need and you can find all the code in description down below now this is one of the features that rails has but you might remember from the introduction that I also message that Redis can do messaging and that is true read this is a pub sub scenario where you can subscribe to char and publish messages into channels and I'm gonna show you as part of this video how you can do that because I think there might be a use case for user so glass-top this application and what I'm gonna do is I'm gonna create a new folder called background tasks and then I'm gonna create a new class here a new long-running task and that would be the Redis subscriber and that will essentially subscribe to Redis and listen for messages in a specific Channel and how to can I do that well I'm gonna using the background service class which allows me to create a real long-running service in dotnet core and in here I'm gonna use my Redis code before I do that let me quickly configure it in the startup so I need to say services dot add hosted service and the type and why is that not allowed here I need to import it so that is now registered so let's write the code that we need to write of course I need to use the I connection multiplexer again so private read-only I connection multiplexer and I need to inject that from the constructor as you would do normally and then in here what I can do is I can say get subscriber and this subscriber now can start consuming messages and how can I do that I can say subscriber dot subscribe and you can also publish me you have many many options but I'm just gonna say subscribe async actually and just return that and then I have to specify the channel I want to I want subscribe to you can also use patterns so if you use star for example you're gonna subscribe to every channel but in here let's just say messages and then you have either some commands or a lambda which is what I will use which is the channel as you can see here and the value that was ported into the channel and in here the only thing I'm gonna do is I'm gonna say console dot write line and then I'm gonna say the message content was and the volume which was the message content and now with that out of the way I'm gonna go ahead and run this as you can see I haven't done anything in readies to make this work I simply said subscribe to this channel and start consuming and just to prove you that the greatest can see still persisted if I do a get I still get my value here so it is properly working how do I publish something well I'm gonna click that button here that allows me to open the console or you can see down here I have the console and I can say publish messages which is my channel name and then the message I want so - not here hi from the console and of course I had to add quotes around that so let me just do that and it says 1 which means probably one person actually received that and as you can see here I actually have the message over to let me spell the message anyway the message content was high from the console so I can just keep doing that if I want and publish any sort of messages this is another one and you can see how many subscribers you have here and somebody can just start consuming these messages on the black background as if it was a message broker so I think that's a very useful other feature that read it has that people don't appreciate as much as they probably should do or use in general the last thing I want to show you is the replication bit because this is another thing that the multiplexer can do in Redis you can have a cluster of nodes and that's very good because your data can be replicated across those nodes and have redundancy and resiliency but as you can see I only started one Redis instance here how do I do another one well if I do a clear as you can see in my daughter PS my service is running on that port named Redis master but I want to add a replica I want to add a slave sorry for the wording it's what Redis is using and how do I do that well I won't bore you with copying a whole command you're gonna find that in the description down below anyway but the command is this it says readies run and I need to specify the external port and the internal port and then I named it as Redis replica and I'm linking it to its master which is the reddest master which you can see here and then I specify that this is a slave and the Masters host is master and then the radius master report is the one specified here I don't have a password and I allow empty password in a realistic scenario you will have a password and ideal it will be behind some firewall as well but in this another local usage I don't have to do this and I'm just gonna run it and as you can see the replica or slave is now running and it also says that it did receive some bytes from the master so let's see what happens if I just quickly refresh that you can see we have a test key here and now we also have the replica and to connect to it I'm just gonna increase the port and I'm gonna call it replica and I'm gonna run it and we can connect and look at that the replica has the exact same key with the exact same value as the master we never put it into that server and that's a completely different radius instance but it is now successfully replicated and let's see what happens if I run this application and actually add a value into the key so this value still exists but if I say test two and say my new value and I run this I can refresh the database and I have two keys but if i refresh the replica database as well I also have two keys now keep in mind my application didn't do that ready state that with the configuration of the slave and the master the replica of the master and currently I'm only using the master in my dotnet application so how do I tell the multiplexer that there's more than one service that it needs to know about well I go to my app settings again and I just copy that and I say coma and I put the new IP the multiplexer will automatically figure out that this is the master and this is a slave so they don't need to be in any specific order and now without here our applications multiplexer will actually know that it has a master slave and will work with both of these databases if needed and the application doesn't change the behavior at all I can add the third key my other value here what's a powder my other and I send it and it all works fine I can simply get the value again you can see my other value and if I go to radius my data is replicated and both of these databases are used by my multiplexer which is awesome that's all I want to cover for this video you're gonna find all the code in the description down below thank you very much for watching especially max to my github sponsors for making these videos possible if you want support as well you're going to find a lady description down below leave a like if you liked this video subscribe for more content like this ring the bell as well to be notified when I upload a new episode and I'll see you in the next video keep coding
Info
Channel: Nick Chapsas
Views: 81,658
Rating: undefined out of 5
Keywords: Elfocrash, elfo, coding, asp.net, .netcore, dot net, core, C#, how to code, tutorial, asp.net core, javascript, 2.2, csharp, rest, rest api, development, lesson, software engineering, dev, microsoft, microsoft mvp, .net core, nick chapsas, chapsas, asp.net core 3, redis, cache, pub/sub, pub sub, redis messaging, redis cache, how to use redis, redis tutorial, redis framework, redis standard, redis core, dotnet, .net
Id: jwek4w6als4
Channel Id: undefined
Length: 18min 39sec (1119 seconds)
Published: Wed Feb 05 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.