在启动时使用Spring缓存注释预填充缓存,以后再使用

时间:2018-08-02 05:37:16

标签: spring caching redis

我正在使用Spring Caching批注设置/获取缓存。

我正在使用以下调用的方法将密钥添加到缓存中。因此,通过延迟加载,将填充缓存的键。

@Cacheable(value = "users", key = "#id")
    @GetMapping("/{id}")
    public User getUser(@PathVariable String id) {
        LOG.info("Getting user with ID {}.", id);
        return userService.getUserById(id);
    }

使用这种方法,我懒于将密钥加载到缓存中。

我希望使用以下方法调用来批量加载值,而不是延迟加载:在服务启动时调用此方法。

 @Cacheable(value = "users")
    public Map<String, String> getAllUsers() {
        LOG.info("Fetching All Users");

        Map<String,String> userMap=new HashMap<>();
        userMap.put("1", "Sam");
        userMap.put("2", "Nike");

        return userMap;

    }

但是,当我访问延迟加载方法以获取数据时填充缓存后,它仍在为要获取的值填充一组不同的键。

我希望该方法在启动时使用从预先填充的缓存中提取数据。

这是使用Spring缓存抽象/注释的可能用例吗,还是应该直接使用Caching API来获取和填充缓存以及获取单个键的值,而不是使用Spring Caching抽象/注释。

0 个答案:

没有答案