I have a spring boot application and i need to store a map in cache. This map can be updated by calling to REST API.
Can i declare a service field and use it with cache?
pom:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
controller:
@PostMapping("updateMap")
@ResponseBody
public ResponseEntity uploadMap(@RequestBody Map<String, Object> data) {
mapService.updateMap(data);
return ResponseEntity.ok();
}
service
// Is it possible to annotate it with @Cachable?
private Map<String, Object> cachedMap;
public void updateMap(Map<String, Object> data) {
//update cachedMap by data
}
public Object getFromMap(String key) {
//get object from map by key
}
CodePudding user response:
Cacheable is an annotation targeted to methods, interfaces and classes. It is not targeted to fields as you intend to use it.
In your service you can create a getMap
method and add the @Cacheable
annotation to it. So everytime this method gets called (outside of the service due to Spring proxy, and apart from the first time that the map does not exist into cache) the map object returned will be the cached one.
@Cacheable("map")
public Map<String, Object> getMap() {
// initialize your Map
cachedMap = new HashMap<>();
cachedMap.put("somekey", "aString");
return cachedMap;
}
And if you want the cache to be updated each time you "update" the map as you do in your controller, then change your public void updateMap(Map<String, Object> data)
:
@CachePut(value = "map")
public Map<String, Object> updateMap(Map<String, Object> data) {
cachedMap.putAll(data);
return cachedMap;
}
@CachePut
will run the method's code anyway and add the returning result into cache.