Spring启动缓存一个字段

Spring boot cache a field

我有一个 spring 启动应用程序,我需要在缓存中存储一​​个地图。可以通过调用 REST API.

来更新此地图

我可以声明一个服务字段并将其与缓存一起使用吗?

pom:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>

控制器:

@PostMapping("updateMap")
@ResponseBody
public ResponseEntity uploadMap(@RequestBody Map<String, Object> data) {
    mapService.updateMap(data);   
    return ResponseEntity.ok();
}

服务

// 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
    }

Cacheable是针对方法、接口和类的注解。它不是针对您打算使用的字段。

在您的服务中,您可以创建一个 getMap 方法并向其添加 @Cacheable 注释。所以每次这个方法被调用(服务之外由于Spring代理,除了第一次地图不存在于缓存中)返回的地图对象将是缓存的。

@Cacheable("map")
public Map<String, Object> getMap() {
    // initialize your Map
    cachedMap = new HashMap<>();
    cachedMap.put("somekey", "aString");
    return cachedMap;
}

如果您希望每次“更新”地图时都更新缓存,就像您在控制器中所做的那样,请更改您的 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 无论如何都会 运行 方法的代码并将返回结果添加到缓存中。