Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Spring Caching annotations on @RestController

  • Can i use Spring caching annotations on top of methods in a RestController.
  • As spring caching is a service level cache but i have a case there is no service so i'm using caching in controller.
  • Is it good to use caching in controller.
  • I'm using cafeine as my underlying cache.
  • I'm thinking that any multithreading issues may happen by using like this caching in controller level.
like image 306
sreedhar Avatar asked Oct 19 '25 10:10

sreedhar


1 Answers

I wouldn't use cacheable("something") in a spring controller that involves user authentication as the cacheable is only keeping arguments. However I do not see any problem if you do not need to cache depending on the user or any request header information.

For example, in the following example, when you are getting the user logged back:

        @RequestMapping(...)
        @Cacheable("something")
        public T analyze(@RequestParam(value = "text") String text) {
        ....
           Object userObj = 
       SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        ....
        }

An option you might have in case you want to cache depending on the header is to add @RequestHeader(value="key") String val in the controller method

like image 184
kimy82 Avatar answered Oct 21 '25 22:10

kimy82



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!