Caching in spring boot rest api | Spring boot cache implementation tutorial from scratch - Part I

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we will have a look at caching support in Spring boot how to configure it and use it to Cache objects update cache and remove objects from cach suppose you have a web application that manages articles you get HTTP requests to save articles update articles fetch articles and delete them these articles are stored in a database now each time a request to fetch an article arrives the application looks over the database and fetches it if there are multiple requests to fetch the same article then it does not make any sense to fetch it from database again and again multiple access to database also makes the application slower a solution to this problem is caching caching means storing objects or data in a separate area this area is called cache Cache can be an in-memory database or a memory location or a server depending on the implementation with caching enabled the application first looks for the required object in the cache instead of fetching it from the database or actual data store if it cannot find the object in cach a only then it accesses the database and once it is fetched it places it inside the cache for future accesses caching is used to make the data access faster since the object or data is fetched from the database only the first time when it is required subsequently it is fetched from the cach A and the database is not accessed thus caching improves the performance of an application spring boot provides support for caching using its starter cache dependencies you can use any of the external cache providers to Cache objects these are the cache providers supported by Spring boot caching if spring boot does not detect any of the cache providers then it uses concurrent hashmap to store data using the default cache provider is not recommended for production but it is fine to understand spring boot caching and we will be doing that in this video separate configuration is required if any of these cache providers is used this video will only cover our default spring boot caching support in the first section of the video we will create a basic rest application with three end points from scratch in the second section we will learn how to and why to add caching support to it if you have not yet subscribed to the channel then do it right away to stay updated open spring tool Su it create a new spring project go to file new project and search for spring starter project select grel as a build tool you can also choose MAV packaging as jar Java version 17 fill in the details such as artifact version description and package click next select spring boot version and select web and cache dependencies click finish you can also do this using spring initializer there are many videos where I've explained explain how to create a spring rest application from scratch link of one such video is at the top right corner the project is generated along with the main class go to projects build. GLE file look here is a dependency for spring boot starter cache now let's go ahead and create rest API endpoints for an article application to fetch update and delete an article first create an article class which will will be the domain object simply add an ID field next create a service class annotate it with service annotation add a method to fetch an article by its ID this method should accept article ID as argument in this video we will simply print a message and not write the business Logic for any of of the methods since its aim is to show how caching works next create a method to update an article this method will accept an object of type article again print a message here finally Define a method to delete an article this will also accept article ID as argument next we will Define end points for each of these methods create a new controller class address controller annotation to make it a spring controller also provide a root URL for all methods of this class using request mapping annotation autoare an object of service class so that its object becomes available here create a method to fetch article this will accept an integer argument its method will be HTTP get so add getmapping annotation over it along with a variable so that we can accept article ID directly from URL value of this variable will be populated from this URL parameter so provide path variable annotation before it this variable in path variable annotation and the parameter in get mapping should match you can learn path variable annotation in detail following the video whose link is at the top right corner call service method next create a method to update an article this method should accept article object as argument and should have request body annotation add a put mapping annotation over this method since this will be an HTTP put method call corresponding service method to update article finally Define a method to delete an article this will also accept article IDE as argument and its value will be fetched from URL so add path variable annotation similar to what we did in Fetch article method since this will be an HTTP delete method method annotation will be delete mapping along with variable to access article ID run the main class the application is running at port 8080 go to postman and access method to get an article by its ID its URL will be Local Host colon 880 SL article SL ID let's say one method will be get send here is the message printed so our rest application is working fine now let's see how to add caching support into this application and what benefit will it provide let's access this URL multiple times you see every time we try to fetch an article it will execute the logic written here to fetch an article it might be fetching it from a database or another HTTP call whatever it is but requires some resources impacting overall application performance a better approach would be that once we fetch a particular record it should store it somewhere and then return the same record for subsequent request that's exactly what we are going to do next using spring boot caching there are a handful of annotation that you need to understand to add caching support to Spring boot applications this annotation is used to inform spring boot that we want to use caching in this application this annotation may be applied over spring boot main class so go to the main class and add this annotation it can also be applied over a spring configuration class if you using the default cache manager and you do not want to customize it then there is no need to create a separate class to apply enable caching annotation after we have informed spring that we need to support caching we need to tell what object we want to cach this is done by using cachable annotation this annotation is applied over a method whose result we want to store in Cache and the return value of that method is automatically cached by spring so in our case we have to apply this over the method that fetches an article with cachable we also need to provide the name of cache where spring would store objects and look for them for retrieval you can provide multiple cache names as an array as well when a request to fetch an article arise spring boot will look for it in the cach named articles if the article is found in cach and this method will not be invoked and if not this method will be called and it will fetch the object as per the logic defined here this also means that for the first time this method will be invoked since the article would not be present in the cache name of the cache is mandatory as the application will fail at runtime with the Java illegal State exception all the objects are cached according to a key if no key is specified then the method parameters are used to create a key so in this case case article ID will be the key against which an article will be cached this is similar to a key in hashmap you can have full control over cache Behavior such as storing objects based on a condition or storing only fixed number of results for this method Etc this becomes a bit Advanced if you would also like to learn these and it will be covered in the coming video on the same topic cashable can also be applied over a class in this case it adds caching Behavior to all the methods of this class and the return values from all the methods are cached cached objects are the copies of original objects and should be identical to them when original object changes then cached object should also be updated this is done using cach put annotation and is applied over a method that performs update operation so in our application it should be applied over the method that is updating the article again we have to provide the name of cache where it will be updating the objects this annotation is used to indicate a remove operation of the data from cache and is applied on the method that deletes object so here it will be applied over the method that deletes object along with the name of cache now let's understand the behavior of these annotations rest start the application back to postman again send the request to fetch article send it multiple times again back to application look only one message is printed which means that it fetched the article only once for subsequent request this method was not even called change the ID of article send message is printed for article id2 again send the request the method is not called which means that the result was cached next send an update request change the URL add a request body select body raw and then Json provide a Json object with ID change the method to put and send the object is updated now let's test delete method provide the article ID in url parameter change the method to delete send the request the object is deleted now if I resend the get request to fetch an article what should happen will the fetch article be called or not pause the video and think write the answer in the comment section below and check if you guess it right the method will be called since we removed the object from cache and when it tries to search in the cache it won't find and call the actual fetch logic that is all for this video in the coming video we will explore more advanced options such as configuring cache at one place caching objects conditionally using unless expiring cachier Etc see you there
Info
Channel: codippa
Views: 2,433
Rating: undefined out of 5
Keywords: cache, caching, rest api, restapi, concurrent hashmap, spring cache, redis, rest app
Id: GZeewuN2EPc
Channel Id: undefined
Length: 12min 5sec (725 seconds)
Published: Sat Oct 28 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.