Spring Scheduler to Create Background Process to make Async Calls to Update Cache in Spring Boot
Using Spring Scheduler to Create a Scheduled Task that hits your Endpoints to Update a Spring Cache for a Spring Boot Application
I used Spring Scheduler to execute a process on a regular basis to make separate async calls to several endpoints to keep the Spring cache updated and also as a health monitor.
This serves two purposes for us, we monitor all the endpoints to ensure correct data is coming back and it keeps the caches fresh and up to date even when there hasn't been traffic on that endpoint recently.
Guides on how to setup Spring caching:
- https://spring.io/guides/gs/caching/
- http://codedevstuff.blogspot.com/2015/07/add-guava-cache-to-spring-boot-to-cache.html
Guide on Spring Scheduler: http://spring.io/guides/gs/scheduling-tasks/
View all the code used in this article on Github here:
Spring Scheduler
You will want to add 3 annotations to your Application.java class. You will need to add annotations for caching, async method calls and scheduling.
Add annotations to your Application.Java class |
Create Scheduled Task
I created a scheduled task here and set the interval that it runs on using Spring Scheduler and the @Scheduled annotation.
The task calls a method which is async and cached which allowed me to call multiple endpoints concurrently. The results of the method call were cached and the success was logged.
I also injected the service to call the async method we are using to get the status of various endpoints.
Create Service for Scheduled Task to use
Get endpoint status is the method called directly from the scheduled task. You can pass in a constant or enum to indicate which endpoint you want to check. Each endpoint will be cached separately because the parameters in the method call are different.
You will need to setup caching in a separate config file. You can view this article on how to setup Spring caching: http://codedevstuff.blogspot.com/2015/07/add-guava-cache-to-spring-boot-to-cache.html
Get endpoint status will then call the correct getStatus() method to check the results of the endpoint. These results will be cached.
This scheduled task can be used with an API or service to regularly check the status and response of various endpoints for health checking or as a regular running integration test of sorts.
View full code below
View the code on Github here:
Code snippets below:
Comments
Post a Comment