my service sometimes need cache data sometimes and sometimes not required , so i would like to write an method that could clear cache when not needed AND #could someone help me creating a restful, java 8 spring boot#
Spring provides annotations that can help you with that purpose. If you conditionally need caching, you could for example use the condition
parameter of the @Cacheable
annotation, for example:
@Cacheable(cacheNames="stuff", condition="#cached")
public List<Stuff> findAll(boolean cached) {
// ...
}
In this case, if you call findAll(true)
, it will return the cached result, while if you call findAll(false)
, it will act as if the annotation isn't there.
Creating a REST API from it isn't that difficult, since your cached
parameter could come from a request parameter as well:
@GetMapping("/api/stuff")
@Cacheable(cacheNames="stuff", condition="#cached")
public List<Stuff> findAll(@RequestParam boolean cached) {
// ...
}
Additionally, if you want to clear the cache, you can use the @CacheEvict
annotation:
@CacheEvict("stuff")
public void clearCache() {
}
And just like before, you can turn this is an endpoint:
@DeleteMapping("/api/stuff/cache")
@CacheEvict("stuff")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void clearCache() {
}